Saturday, August 19, 2017

Producer Consumer example in Java?

Producer consumer problem is a design pattern. In java BlockingQueue is used to implement producer consumer designer pattern.

Producer is keep on placing the items or tasks in the Queue until its size become full and consumer will keep consume the tasks in queue until queue size becomes zero.

Here I am providing the producer consumer example in Java.

Producer.java

import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

 public class Producer implements Runnable{

           private final BlockingQueue sharedQueue;
 
          public Producer(BlockingQueue sharedQueue){
                this.sharedQueue=sharedQueue;
          }

         @Override
          public void run() {
               for(int i=0;i<10;i++){
                     System.out.println("Produced.."+i);
                     try {
                             sharedQueue.put(i);
                     } catch (InterruptedException e) {
                             Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e);   }
                     }
  
           } 
    }

Consumer.java

import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

 public class Consumer implements Runnable{
 
            private final BlockingQueue sharedQueue;
 
            public Consumer(BlockingQueue sharedQueue){
                    this.sharedQueue=sharedQueue;
            }

            @Override
            public void run() {
                     while(true){
                                         try {
                                                  System.out.println("Consumed.."+sharedQueue.take());
                                               } catch (InterruptedException e) {
                                                   Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e);
                                               }
                                        }  
           }

     }

producerConsumerDemo.java

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

 public class producerConsumer{
            public static void main(String[] args) {
                    BlockingQueue sharedQueue = new LinkedBlockingQueue();
  
                    Thread prodThread = new Thread(new Producer(sharedQueue));
                    Thread consThread = new Thread(new Consumer(sharedQueue)); 
  
                     prodThread.start();
                     consThread.start();
            }

}


No comments: