Saturday, 10 August 2013

producer and cosumer problem in java

simple program for producer consumer problem:


we have three programs to implement producer consumer problem
 first program for producer:

public class producer implements Runnable
{
   private Thread t;
   private Queue q1;
   public producer(Queue c)
   {
      q1=c;
      t=new Thread(this,"producer");
      t.start();
  }
public void run()
{
   int i=0;
   while(true)
    {
      q1.put(i);
      i++;
     System.out.println("inserted element" +i);
try
 {
   Thread.sleep(1000);
 }
catch(Exception e)
{
  System.out.println("Exception " +e);
}
}
}
}



second program for Consumer

public class consumer implements Runnable
  private Thread t;
  private Queue q1;
public consumer(Queue c)
{
q1=c;
t=new Thread(this,"consumer");
t.start();
}
public void run()
{
int x;
while(true)
{
x=q1.get();
System.out.println("deleted element" +x);
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
System.out.println("exception" +e);
}
}
}
}




third program for Queue

public class Queue
{
 private int f;
 private int r;
 private int q[]=new int[10];
 private boolean empty;
 private boolean full;
 
public Queue()
{
 f=-1;
  r=-1;
   empty=true;
   full=false;
}
synchronized public void put(int x)
  { 
    try 
        {
          if(full)
            
              wait();
            
           
              
                r=(r+1)%10;
                q[r]=x;
                empty=false;
               
               if(f==-1)
               {      
                  f=0;
                  notify();
                  
               }
          }
     catch(Exception e)
              {
                 System.out.println("exception" +e);
             }
     }
synchronized public int get()
{
  try
     {
       if(empty)

          wait();
  
     

   int x;
        x=q[f];      
        if(f==r)
        {
          empty=true;
           f=r=-1;
         }
       else
           {
             f=(f+1)%10;
}
             full=false;
              notify();
            return x;
            }        
 catch(Exception e)
      {             
       System.out.println("exception" +e);
       return -1;
     }
}

}



save all program in same drive and complie

No comments:

Post a Comment