1. Two threads can communicate with each other by using wait(), notify(), notifyAll().
  2. These methods are available in object class but not in thread class because threads can call these methods on any object.
  3. We should call these methods only from synchronized area other wise we get runtime exception saying IllegalMonitorStateException.
  4. If a thread executes wait() method it immediately releases the lock of that object(But not all locks) and entered into waiting state.
  5. After giving the notification also the thread releases the lock but may not be immediately.

Methods:

  1. public final void wait() throws InterruptedException
  2. public final void wait(long ms) throws InterruptedException
  3. public final void wait(long ms, int ns) throws InterruptedException
  4. public final void notify()
  5. public final void notifyAll()

InterThreadCommunication
Example:

public class MainThread {
	 
    public static void main(String[] args)throws InterruptedException {
        ChildThread thread=new ChildThread();
        thread.start();
        synchronized (thread) {
            System.out.println("Main Thread calling Child thread");
            thread.wait();
            System.out.println("MainThread got notification");
            System.out.println(thread.total);
        }
    }
 
}
 
class ChildThread extends Thread {
    int total = 0;
 
    public void run() {
        synchronized (this) {
            System.out.println("Child thread calculating");
            for (int i = 0; i <= 100; i++) {
                total = total + i;
            }
            System.out.println("ChildThread giving notofication");
            this.notify();
        }
    }
     
}
/*
Output:
Main Thread calling Child thread
Child thread calculating
ChildThread giving notofication
MainThread got notification
5050
*/