Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 709
Kyle Xie Avatar asked Oct 04 '12 01:10

Kyle Xie


1 Answers

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

like image 189
Ярослав Рахматуллин Avatar answered Oct 06 '22 00:10

Ярослав Рахматуллин