Inter thread communication
Inter-thread communication can be defined as the exchange of messages between two or more threads. The transfer of messages takes place before or after the change of state of a thread. For example, an active thread may notify to another suspended thread just before switching to the suspend state.
The wait( ), notify( ) and notifyAll( ) methods are used to establish the inter-thread communication. When the wait( ) method is invoked inside a synchronized method or synchronized block, the object lock that is held by the the current thread is temporarily released. In addition, the current thread is deactivated. As a result, the current thread is made to wait. This activity allows another thread to acquire the object lock.
The notify( ) method or the notifyAll( ) method brings back a thread from the waiting state to the ready state. When we use the notifiAll( ) method, all the waiting threads will move from the waiting state to the ready state. But the notify( ) method randomly picks just one of the waiting threads and moves it from the waiting state to the ready state. This method will be useful only when every waiting thread can immediately resume its work. But, in reality, one or more threads can resume their work only after some other threads partially or fully complete their work. Due to this reason, it is always advisable to use the notifyAll( ) method for unblocking the waiting threads.
The wait( ), notify( ), and notifyAll( ) methods are declared in the super class of Object. Since, the methods are declared as final they cannot be overridden. All the three methods throw InterruptedException.
Program
class NewThread extends Thread{ NewThread() { start(); } public void run() { synchronized(this) { for(int i=0;i<5;i++) { System.out.println("Child Thread Running..."+i); } System.out.println("Exiting Chiled Thread"); notify(); } } } public class Javaapp { public static void main(String[] args) { NewThread child = new NewThread(); synchronized(child) { try{ System.out.println("Main Thread Waiting for Child Thread to Complete..."); child.wait(); System.out.println("Notification Received From Child Thread"); }catch(InterruptedException ie) { System.out.println("Thread Interrupted"); } } System.out.println("Exiting Main Thread"); } }