java.lang.Object notify() - does it notify a thread at random, or the first one to call wait()?

StackOverflow https://stackoverflow.com/questions/18045494

  •  23-06-2022
  •  | 
  •  

Pergunta

Say I have 3 threads (A, B, and C) that are waiting for the monitor on an object O. Thread D currently has the monitor for Object O. When thread D calls O.notify, which thread gets notified first? A, B, or C? Is it based off the first of those threads to call wait() on object O? Perhaps I am speaking about the difference between notify() and notifyAll()? If I were to guess, notify() would notify the first thread to call wait() and notifyAll() would notify all threads that called wait() AND the next thread to get the monitor would basically be at random?

Foi útil?

Solução

It's any thread which is waiting on the monitor. From section 17.2.2 of the JLS:

There is no guarantee about which thread in the wait set is selected. This removal from the wait set enables u's resumption in a wait action. Notice, however, that u's lock actions upon resumption cannot succeed until some time after t fully unlocks the monitor for m.

And from the Object.notify docs:

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top