Pages

Ads 468x60px

Monday 17 December 2012

Producer consumer problem using inter thread communication



18. WAJP that correctly implements Producer-Consumer problem using the concept of Inter Thread Communication.
Program:
                                         program for inter thread communication
class Producer extends Thread
{
  static int i=0;
 
  Consumer obj;
 
  Producer(Consumer obj1)
  {
   obj=obj1;
  }
 
  public void run()
  {
   System.out.println("producer thread started");
  
   synchronized(obj)
   {
  
    while(true)
    {
    try
  
     {
      System.out.println("Value produced is:"+(i+1));
     
      obj.j=++i;
     
      Thread.sleep(10);
     
      wait();
     
      System.out.println("lock is released by producer");
    }catch(Exception e)
    {
    }
   }
  }
 }
}

class Consumer extends Thread
{
 int j;

 public void run()
 {
  System.out.println("consumer thread has been started");
 
  synchronized(this)
  {
   while(true)
   {
    try
    {
     System.out.println("value of j before exception"+j);
    
     Thread.sleep(10);
    
     System.out.println("consumed:"+j);
    
     notify();
   }catch(Exception e)
   {
   }
  }
 }
}

}
class CommDemo
{
 public static void main(String[] args)throws Exception
 {
  Consumer con=new Consumer();
 
  Producer pod=new Producer(con);
 
  con.start();
 
  Thread.sleep(5);
 
  pod.start();
 }
}           

0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text