Home » Java Basics » 06 - Threads and GUIs
6

Object wait, notify, and notifyAll

How to use the object wait, notify and notifyAll

The wait, notify, and notifyAll methods allow threads to coordinate their actions. Sometimes, a thread may have to wait until a certain condition is true before proceeding. Consider a thread that continually processes messages in a queue. This thread should wait until a new message arrives before the actual processing. The wait() method suspends the current thread until another thread issues notify() or notifyAll() (notify() simply communicates with one thread while notifyAll() communicates with all waiting threads):

public synchronized messageProcessor() {
while(!messageSent) {
try {
wait();
} catch (InterruptedException e) {}
}
.
.
(Message Processing Code)
.
.
}
 
public synchronized messageSender() {
sendMessageToQueue();
messageSent = true;
notifyAll();
}

Note: The wait, notify, and notifyAll methods are usually used in synchronized blocks. A waiting thread needs a lock on the objects and on the operations that should not be processed unless the condition is satisfied. If the loop is not synchronized, other objects may get into the objects and code before the condition is satisfied.