简体   繁体   中英

How wait/notify and Condition manage threads

I understand that the wait() and notify()/notifyAll() methods serve the purpose of replacing the traditional looping/polling constructs used in other languages:

while(true) {
    if(pollSomethingForAnEvent())
        break;
}

I further understand that the Condition API was introduced in Java 5 to be wrap this model in a more "OO" implementation.

What I don't understand is how Java knows which threads to notify when Object.notify() or Condition.signal() is called, or how Java knows which threads to signal with Object.wait() or Condition.await() is called?

Since these methods don't take anything as parameters, how does the JVM know which threads to pass these notifications to?!?!

For each Condition or synchronized object, the JVM maintains a queue of objects that are waiting on them. It also has run queues and other data structures which maintain and manage the Thread run states.

When Object.notify() is called, it just looks in the queue associated to the object at takes the first Thread there and moves it to the run queue. If the queue is empty then no threads are notified. If notifyAll() is called then all threads that are waiting on that object are signaled.

Not to complicate matters, but one thing that is important to realize is that when a Thread that called lockObject.wait() is notified, it moves from a wait state to the end of the run queue waiting to get access to the lock on lockObject . It does not start running immediately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM