Wednesday, March 25, 2009

What is Interthread communication in Java?

Interthread communication
In Java for interthread communication there are methods provided in Object class called wait, notify, notifyall. Since they are in Object class they are available to all the classes in java. These methods should always be called from inside a synchronized block or else there will be an exception, IllegalMonitorException. When a thread is waiting to get a lock on an object it calls wait on that object .

There are three ways in which Threads communicate with each other :

wait: It tells the calling thread to give up the monitor until some other thread enters the same monitor an calls Notify or Notifyall.

notify: It wakes up the first thread that called Wait() on the same object.

NotifyAll: It allows all the threads that called Wait() on the same object.The thread having the highest priority will run first.

Example

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=true;
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);
}
}

No comments: