Trying to understand wait()
and notify()
. I know when thread A
went to wait()
it will be waked up by notify()
from other thread.
But what will happens if threads A
,B
,C
went to wait()
in represented order? Who will be waked up by notify()
? According to my experiments A
thread will be waked up at first. I'm right?
Does it means that system knows in which order threads went to wait()
?
From the documentation for notify()
, emphasis mine:
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. A thread waits on an object's monitor by calling one of the wait methods.
Some other APIs, such as Semaphore
, have a concept of "fairness", where you can ensure that threads do proceed in the order in which they blocked.
Section 17.2.2 Notification of Java Language Specification:
There is no guarantee about which thread in the wait set is selected.
So, observed behavior is not guaranteed and should not be relied upon.
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