The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for notification, and we use the notify() method, only one thread will receive the notification, and the others will have to wait for more. This method does not return any value.
It is used with the wait() method, in order to communicate between the threads as a thread that goes into waiting for state by wait() method, will be there until any other thread calls either notify() or notifyAll() method.
Syntax
public final void notify() ;
Return: No return value
Exception
IllegalMonitorStateException: This exception throws if the current thread is not
owner of the object's monitor
Implementation:
- The synchronized keyword is used for exclusive accessing.
- wait() instructs the calling thread to shut down the monitor and sleep until another thread enters the monitor and calls notify().
- notify() wakes up the first thread that is called wait() on the same object.
Example of Java notify() Method
Java
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Thread2 objB = new Thread2();
objB.start();
synchronized (objB)
{
try {
System.out.println(
"Waiting for Thread 2 to complete..." );
objB.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( "Total is: " + objB.total);
}
}
}
class Thread2 extends Thread {
int total;
public void run()
{
synchronized ( this )
{
for ( int i = 0 ; i < 10 ; i++) {
total += i;
}
notify();
}
}
}
|
OutputWaiting for Thread 2 to complete...
Total is: 45