Search This Blog

producer consumer problem in java

class Q
{
int n=0;
boolean value=false;

synchronized void get()
{
  while(!value)
{
try{
 wait();
Thread.sleep(1000);
   }
catch(InterruptedException e) { }
}

System.out.println("Get got notification"+" :Thread name :"+Thread.currentThread().getName());
System.out.println("Got :"+n);
n++;
value=false;
notify();
}

synchronized void put()
{
  while(value)
{
try{
 wait(1000);
Thread.sleep(1000);
   }
catch(InterruptedException e) { }
}
System.out.println("put got notification"+" : Thread name :"+Thread.currentThread().getName());
System.out.println("put :"+n);

value=true;
notify();
}
}
class producer implements Runnable
{
Q putthread;
producer(Q q)
{
 this.putthread=q;
new Thread(this,"producer").start();
}
public void run()
{
for(int i=0;i<10 i="" p="">{
   putthread.put();
}
}
}
class consumer implements Runnable
{
Q getthread;
consumer(Q q)
{
 this.getthread=q;
new Thread(this,"consumer").start();
}
public void run()
{
for(int i=0;i<10 i="" p="">{
   getthread.get();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Q q=new Q();
System.out.println("OUTPUT OF PRODUCER CONSUMER PROBLEM");
new producer(q);
new consumer(q);
}
}


OUTPUT:

Description:
producer consumer is a famous problem in multithreadding, in which there are two threads,eg. here producer and consumer.producer thread is responsible to produce items to the Queue and consumer thread is responsible to consume threads from a Queue.
                        In this program i have demonstrated producer consumer problem with the help of two methods of the class Q,
1:synchronized void get()
2:synchronized void put()
                     get() method is executed by consumer thread and put() method is executed by producer thread.
                     For the first time if the put() method got chance first it produces elements to the Queue  and sets variable value=true, which means if it gets chance once more before the consumer , it will call wait() method and enter into waiting state.Thus  the producer thread releases lock when it calls wait method. consumer thread gets the lock  of the object(q here) and consumes that element from a Queue ,and notifies the producer thread to execute by calling notify() method,thus the producer thread resumes.
                    If the consumer thread will get the chance first thus there will will be no elements in a Queue,it calls wait() method (because !value=true) and gives up the lock of the Q object. producer thread gets the lock of this object and produces elements to the Queue and also it calls notify() method to notify the consumer thread,thus  consumer thread resumes.

No comments:

Post a Comment

leave a comment here