Interthread communication

Java implements a very efficient way to interprocess communication among threads which reduces the CPU?s idle time i.e.

Interthread communication

Java implements a very efficient way to interprocess communication among threads which reduces the CPU?s idle time i.e.

Interthread communication

Interthread communication

     

Java implements a very efficient way to interprocess communication among threads which reduces the CPU?s idle time i.e. A process where, a thread is paused while running in its critical region and another thread is allowed to enter (or lock) in the same critical section to be executed.  This technique is known as Interthread communication which is implemented by some methods. These methods are defined in "java.lang" package and can only be called  within synchronized code shown as:

 Method  Description
 wait( )  It indicates the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls method notify() or notifyAll().
 notify( )  It wakes up the first thread that called wait() on the same object.
 notifyAll( )  Wakes up (Unloack) all the threads that called wait( ) on the same object. The highest priority thread will run first.

All these methods must be called within a try-catch block.

Lets see an example implementing these methods :

 

class Shared {

int num=0;
boolean value = false;
  
synchronized int get() {
  if (value==false
  try {
  wait();
  }
  catch (InterruptedException e) {
  System.out.println("InterruptedException caught");
  }
System.out.println("consume: " + num);
value=false;
notify();
return num;
}

synchronized void put(int num) {
  if (value==true
  try {
  wait();
  }
  catch (InterruptedException e) {
  System.out.println("InterruptedException caught");
  }
  this.num=num;
  System.out.println("Produce: " + num);
  value=false;
  notify();
  }
  }

  class Producer extends Thread {
  Shared s;
  
  Producer(Shared s) {
  this.s=s;
  this.start();
  }

  public void run() {
  int i=0;
  
  s.put(++i);
  }
}

class Consumer extends Thread{
  Shared s;
  
  Consumer(Shared s) {
  this.s=s;
  this.start();
  }

  public void run() {
  s.get();
  }
}

public class InterThread{
  public static void main(String[] args
  {
  Shared s=new Shared();
  new Producer(s);
  new Consumer(s);
  }
}

Output of the Program:

C:\nisha>javac InterThread.java

C:\nisha>java InterThread
Produce: 1
consume: 1

In this program, two threads "Producer" and "Consumer" share the synchronized methods of the class "Shared". At time of program execution, the "put( )" method is invoked through the "Producer" class which increments the variable "num" by 1. After producing 1 by the producer, the method "get( )" is invoked by through the "Consumer" class which retrieves the produced number and returns it to the output. Thus the Consumer can't retrieve the number without producing of it. 

Download this Program