wait(), notify(), and notifyAll()
What happens when there is more than one thread waiting for the notification? Which thread actually gets the notification when notify() is called? The answer is that it depends: the Java specification doesn’t define which thread gets notified. Which thread actually receives the notification varies based on several factors, including the implementation of the Java virtual machine and scheduling and timing issues during the execution of the program. There is no way to determine, even on a single platform, which of multiple threads receives the notification.
There is another method of the Object class that assists us when multiple threads are waiting for a condition:
- void notifyAll()
Notifies all the threads waiting on the object that the condition has occurred. This is a method of the Object class and must be called from within a synchronized method or block.
The Object class also provides the notifyAll()
method, which helps us in those cases where the program cannot be
designed to allow any arbitrary thread to receive the notification.
This method is similar to the notify() method,
except that all of the threads that are waiting on the object will be
notified instead of a single arbitrary thread. Just like the
notify() method, the
notifyAll() method does not let us decide which threads get notification: they all get notified. By having all the threads receive notification, it is now possible for us to work out a mechanism for the threads to choose ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access