Inter Thread Communication

Aim: 
To write a java program that correctly implements Producer consumer problem using the concept of inter thread communication.

Description:
In some cases two or more threads should communicate with each other. One thread output may be send as input to other thread. For example, a consumer thread is waiting for a Producer to produce the data (or some goods). When the Producer thread completes production of data, then the Consumer thread should take that data and use it. In producer class we take a StringBuffer object to store data, in this case; we take some numbers from 1 to 5. These numbers are added to StringBuffer object. Until producer completes placing the data into StringBuffer the consumer has to wait. Producer sends a notification immediately after the data production is over.

Program:
class Producer implements Runnable
{ StringBuffer sb;
Producer ()
{ sb = new StringBuffer();
}
public void run ()
{
synchronized (sb)
{
for (int i=1;i<=5;i++)
{ try
{
sb.append (i + " : ");
Thread.sleep (500);
System.out.println (i + " appended");
}
catch (InterruptedException ie){}
}
sb.notify ();
}
}
}
class Consumer implements Runnable
{ Producer prod;
Consumer (Producer prod)
{ this.prod = prod;
}
public void run()
{ synchronized (prod.sb)
{ try
{
prod.sb.wait ();
}
catch (Exception e) { }
System.out.println (prod.sb);
}
}
}
class Communicate
{
public static void main(String args[])
{
Producer obj1 = new Producer ();
Consumer obj2 = new Consumer (obj1);
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t2.start ();
t1.start ();
}
}