Imagine I have 3 threads with a wait condition, and a 4th thread with a notify condition.
Now, all 3 wait threads run and enter a waiting state. Once this is done, the 4th thread runs and calls notify once.
How will the notify determine which thread to wake up? Is it the thread that called wait first thread, the thread that called wait last, or is it based on some other condition?
Assume that wait and notify uses same lock.
See documentation for notify() method. Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor. A thread waits on an object's monitor by calling one of the wait() method.
The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for notification, and we use the notify() method, only one thread will receive the notification, and the others will have to wait for more. This method does not return any value.
notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.
To my knowledge, there is no special bookkeeping - meaning that the selection is made "randomly".
So says the javadoc:
If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
Thus it would be theoretically possible that a JVM implementation decides to enact a specific order; but as shown - by default you can't expect any order. So you shouldn't write code that relies on such an specific order either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With