What does a thread do after calling wait() in Java?

空扰寡人 提交于 2019-12-10 15:04:35

问题


In multi-threading programs, I suspect that when a thread wait(), it does not engage much cpu utilization so that the cpu can swap to process other thread.

For example, 100 threads start the same task together comparing to 50 threads actually do the task while other 50 threads wait until all 50 tasks are completed. The latter case cost much less time than the former.

Can anyone suggest some readings about this?


回答1:


The wait method has two purposes:

  1. It will tell the currently executing thread go to sleep (not use any cpu).
  2. It will release the lock so other threads can wake up and take the lock.

Whenever a method does something inside a synchronized block, whatever is in the block must wait for the locked object to be released.

synchronized (lockObject) {
    // someone called notify() after taking the lock on
    // lockObject or entered wait() so now it's my turn

    while ( whatineedisnotready) {
        wait(); // release the lock so others can enter their check
        // now, if there are others waiting to run, they 
        // will have a chance at doing so.
    }
}

Must-Read:

java synchronized



来源:https://stackoverflow.com/questions/12719054/what-does-a-thread-do-after-calling-wait-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!