|
We saw how notify() method notifies the thread waiting for notification. But a shared object may have multiple threads that are waiting to be notified. For example, there can be several stock analyzer threads that are analyzing a common stock object ( For example, stock of company ACME) . Therefore all of them might be waiting for the notification whenever the stock (price) is changed. When the stock modifier modifies the price it may notify with a call notify().But this method picks only one of the waiting threads (in no guaranteed order) and notifies it.
Often, you want to notify all of them. In that case, you need to use the notifyAll() method. For example, if you use stock.notifyAll(), all the waiting threads (on stock object) will come out of the waiting area and will be back to ready-to-run state. notifyAll() can not make them all run immediately as they need to reacquire lock on stock object which can be done one at a time. But they all will definitely know that stock object is changed. Figure 12.17 shows the difference between notify and notifyAll().
![]() |
Figure 12.17 notify() method notifies any one of the waiting threads whereas notifyAll() notifies all of them
In case of notify() any one of the waiting threads can be notified and there is absolutely no guarantee which one it will be as it depends on the JVM implementation. Therefore there is no way to specifically notify a particular thread. If you want to guarantee a notification to a particular thread, the best way is to broadcast your notification with notifyAll(). That way you can be sure that the intended thread gets it.
|
@ |
Once the threads are notified, they start contending for CPU (turn to execute) and the lock . One of them will get the lock and rest of them will enter another pool (of threads waiting to get the lock). Eventually each one of them will acquire the lock and continue its execution. Thus a call notify() or notifyAll() does not mean that the threads waiting on it will start executing immediately. |