This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I am currently studying threads and synchronization. What I have not been able to figure out a detail in the difference between notify and notifyAll. I read that notifyAll() notifies all the threads that are waiting, and that notify() notifies only one thread waiting. I have no problem understanding who notifyAll() works. - What if I call notify() and there are several threads waiting? * How would the system determine what thread must be notified? * Would it be an error to call notify() if there are several threads waiting? Thanks in advance for your feedback!! -Juan Carlos
- What if I call notify() and there are several threads waiting?
Then only one gets notified. The others stay suspended, and won't wake up until they are notified in turn.
* How would the system determine what thread must be notified?
As it says in the Javadoc, "The choice is arbitrary and occurs at the discretion of the implementation."
* Would it be an error to call notify() if there are several threads waiting?
It depends on the application. notify() might mean that, for example, one unit of work was ready to process; the notified threads might be "worker threads" waiting to do work. So in this case "notifyAll" would clearly be wrong; you'd just want to notify one waiting thread, and the others could stay suspended.