Java implements a very efficient interprocess communication which reduces the CPU’s idle time to a very great extent. It is been implemented through wait ( ), notify ( ) and notifyAll ( ) methods. Since these methods are implemented as final methods they are present in all the classes.
The basic functionality of each one of them is as under:
■ wait( ) acts as a intimation to the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
■ notify( ) is used as intimator to wake up the first thread that called wait( ) on the same object.
■ notifyAll( ) as the term states wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.
public class WaitNotifyAllExample { public static void main(String[] args) { try { Object o = new Object(); Thread thread1 = new Thread(new MyOwnRunnable("A", o)); Thread thread2 = new Thread(new MyOwnRunnable("B", o)); Thread thread3 = new Thread(new MyOwnRunnable("C", o)); // synchronized keyword acquires lock on the object. synchronized (o) { thread1.start(); // wait till the first thread completes execution. // thread should acquire the lock on the object // before calling wait method on it. Otherwise it will // throw java.lang.IllegalMonitorStateException o.wait(); thread2.start(); // wait till the second thread completes execution o.wait(); thread3.start(); } } catch (InterruptedException e) { e.printStackTrace(); } } } class MyOwnRunnable implements Runnable { private String threadName; private Object o; public MyOwnRunnable(String name, Object o) { threadName = name; this.o = o; } public void run() { synchronized (o) { for (int i = 0; i < 1000; i++) { System.out.println("Thread " + threadName + " Count : " + i); } // notify all threads waiting for the object o. // thread should acquire the lock on the object // before calling notify or notifyAll method on it. // Otherwise it will throw java.lang.IllegalMonitorStateException o.notifyAll(); } } }