Sunday, 2 March 2014

Producer Consumer Problem

The wait/notify mechanism allows one thread to wait for a notification from another thread to proceed.

For Example consider producer-consumer problem, producer produces the items, and consumer consumes the items produced by the producer

Basic scenarios to be considered in producer consumer problem.

1. Consumer can't consume the items, if the items are not produced by producer. So consumer must wait until the producer produces items. So consumer calls the wait method of the producer object.

2. Once the consumer consumes the items, he must notify the producer, so producer produce the items.

3. Producer must wait until the consumer consumes the items.

4. Once the producer produces the items, then he must tell the consumer, Please consume the items. So he must notify the consumer.

Solving a Producer-Consumer Problem
class Queue{
 int noItems;
 boolean flag = true;

 void produce()throws Exception{
  if(flag){
   noItems++;
   System.out.println("Produced " + noItems);
   flag = false;
   notify();
  }
  else{
   wait();
  }
 }

 void consume()throws Exception{
  if(!flag){
   System.out.println("Consumed " + noItems);
   flag = true;
   notify();
  }
  else{
   wait();
  }
 }
}

class Producer implements Runnable{
 Queue q;
 public void run(){
  while(true){
   try{
    q.produce();
   }
   catch(Exception e){
   }
  }
 }

 Producer(Queue q){
  this.q = q;
 }
}

class Consumer implements Runnable{
 Queue q;

 public void run(){
  while(true){
   try{
    q.consume();
   }
   catch(Exception e){
   }
  }
 }

 Consumer(Queue q){
  this.q = q;
 }
}

class Test{
 public static void main(String args[]){
  Queue q = new Queue();

  Producer prod = new Producer(q);
  Consumer con = new Consumer(q);

  Thread t1 = new Thread(prod);
  Thread t2 = new Thread(con);

  t1.start();
  t2.start();
 }
}
   
Sample Output
Produced 1
Consumed 1
Produced 2
Consumed 2
Produced 3
Consumed 3
Produced 4
Consumed 4
Produced 5
Consumed 5
Produced 6
Consumed 6
Produced 7
Consumed 7
......
......

Explanation
There are four classes
    Queue Class
    Producer class
    Consumer class
    Test class

Queue class
Queue class object is the shared resource that is shared between producer and consumer. It has two methods, produce(), consume().

If flag is true,  producer start producing the items. The same logic implemented in produce().After producing the items, producer sets the flag to false, and notifies the consumer. So consumer consumes the item, sets the flag to true, and notifies the producer.

Producer class
Producer class calls the produce(), infinitely.

Consumer class
Consumer class calls the consume(), infinitely.

Test class
Test class tests the application of producer and consumer.   



Thread Join                                                 Thread wait: Release resources                                                 Home

No comments:

Post a Comment