Thread Communication in Java – wait(), notify(), notifyAll()

In Java Threads can community with each other by using wait(), notify(), and notifyAll(). The Thread which is excepting updation is responsible to come wait(), Then immediately the Thread will enter into a waiting state

The Thread which is responsible to perform the update after performing the updation it’s responsible to call notify method the waiting Thread will get that notification and continue its execution with those updated items.

wait(), notify(), and notifyAll() methods are present in the Object class but not in the Thread class because the Thread can call these methods in any Java object.

to call wait(), notify(),notifyAll() methods on any Object, Thread should be the owner of that object i.e., Thread should have lock of that object i.e Thread should be inside Synchronized area., Hence we can call wait(), notify(), and notifyAll() only from the Synchronized area otherwise we will get a run time exception

If a Thread calls the wait() method on any object it immediately releases the lock of a particular object and enters into waiting state.

if a Thread calls notify() on any object then it releases the lock of that object but may not immediately except wait(), notify(), and notifyAll() there is no other method where Thread releases the lock

MethodIs Thread released the lock?
yield()No
join()No
sleep()No
wait()Yes
notify()Yes
notifyAll()Yes

Methods Related to wait(), notify(), notifyAll()

public final void wait()
 throws InterruptedException
public final void wait( long timeoutMillis )
 throws InterruptedException
public final void wait( long timeoutMillis,
int nanos )
 throws InterruptedException
public final void notify()
public final void notifyAll()

Note – Every wait() throws InterruptedException which is a checked Exception, Hence whenever we are using wait() compulsory we should handle this InterruptedException either by try-catch block or by throw keyword, otherwise we will get Compile time Error

Thread Communication Java Example

 public class MyThread extends Thread {
     int total = 0;

     @Override
     public void run() {
         synchronized (this) {
             System.out.println("Child thread start calculation");
             for (int i = 0; i <= 100; i++) {
                 total = total + i;
             }
             System.out.println("Child Thread is going to notify");
             this.notify();
         }
     }
 }
class ThreadCommunication {

    public static void main(String[] args) throws InterruptedException {
        MyThread T1 = new MyThread();
        T1.start();
        synchronized (T1) {
            System.out.println("Main Mwthod calling wait method");
            T1.wait();
            System.out.println("Main Method got notification ");
            System.out.println(T1.total);
        }
        }
    }
Thread Communication Java Example

Similar Java Tutorials