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

2019-06-21 04:52发布

问题:

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