Last Updated:

An example of using wait(), notify() and notifyAll() in Java.

A thread that calls these methods on any object must have what is known as a monitor (a multithreaded object access mechanism). If it is not, then an exception will be thrown.java.lang.IllegalMonitorStateException

Wait() method

The method has three variations. One method waits indefinitely for another thread until the method is called or on an object. The other two variations of the method put the current flow on hold for a specific time. After this time, the stream wakes up and continues to work.wait()wait()notify()notifyAll()wait()

Notify() method

Calling the method wakes up only one thread, and then the thread starts execution. If an object is waiting for multiple threads, the method will wake up only one of them. The choice of thread depends on the system implementation of flow control.notify()notify()

NotifyAll() method

The method wakes up all threads, although in what order they will be awakened depends on the implementation of the OS.notifyAll()

Methods , and . Practicewait()notify()notifyAll()

Let's look at the use of the methods , and .wait()notify()notifyAll()

Below is the Java Bean on which our streams will run:

First, let's write a class that will wait for other threads until they finish executing. Let's call it Waiter. This class will host the monitor on the Message object using the synchronizing block.

Next, let's create a Notifier class that will process the Message object, and then call the notify method to wake up the messages that are waiting.

Now let's write a test class that will create several Waiter and Notifier threads.

When we run this program, we will see the progress of its implementation in the console, but it will not finish the work. The fact is that there are two threads that are waiting on the Message object, and the method will wake up only one of them – the other thread is still waiting for its notification.notify()

The result of the execution using the method :notify()

Now let's comment out the call and uncomment the call in the Notifier class. After that, run the program again.notify()notifyAll()

The result of the execution using the method :notifyAll()

As you can see above, after the call, all threads worked out and the program completed execution.notifyAll()