|
|
The Wait-Notify Primitive A thread enters the queue associated with the object monitor by calling wait() inside one of the methods in an object, or explicitly performing a anObject.wait() operation. If a thread is put into the queue by calling wait(), it can't be scheduled for execution (i.e. it is in the runnable state) until some other thread calls notify()/notifyAll() on the object it has been waiting for. If there are multiple threads waiting on the object, on the reception of a notifyAll(), all of them are now in the Runnable state. The Java scheduler schedules the thread with the highest priority for execution. There exists a subtle difference between the notify() and notifyAll() primitive. The notify() method reports to one arbitrary thread among the several waiting on the object. The notifyAll() method on the other hand reports to all the threads. By having all the threads receiving this notification, we can work out a mechanism where the threads can choose among themselves which thread should continue and which should call the wait() again. All the waiting threads wakeup, but they still have to acquire the object lock. So the threads must wait for the object lock to be freed. Thus only one thread can run at a time, and only after the thread that called the notifyAll() method releases its lock. With notifyAll() we cannot really control which threads wake up, instead we are control which thread get to wakeup after all the threads have received notification. This approach tends to be ineffectual, if there are many threads waiting to receive notification Source
JAR Files: Please refer to the Java-Basics section for more information on using JAR files. |