Java Producer Consumer Problem using BlockingQueue

In java we use BlockingQueue to create a Queue that is shared by both producer and consumer. Here is an example of same.


import java.util.concurrent.BlockingQueue;

public class ProduConsumTestBlockngQueue {
 
 public void Produce (BlockingQueue  bqueue) {
  int x= (int) (Math.random()*10+2);
  for (int i=0;i  bqueue) {
  
  
  while(bqueue.remainingCapacity() >=1) {
  
  try {
   while(true) {
   Integer item = bqueue.take();
   System.out.println("Consumed---"+item+Thread.currentThread().getName());
   Thread.sleep(100);
   }
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
  
 }}

Main class to Test Same


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MainProd {
 
 
 public static void main(String [] args) {
  
  BlockingQueue bqueue = new ArrayBlockingQueue<>(3);
  final ProduConsumTestBlockngQueue prod = new ProduConsumTestBlockngQueue();
  
  Thread t1 = new Thread(new Runnable() {

   @Override
   public void run() {
    prod.Produce(bqueue);
   }
   
  });
  
  Thread t2 = new Thread(new Runnable() {

   @Override
   public void run() {
    prod.consume(bqueue);
   }
   
  });
  
  t1.start();
  t1.setName("Prod");
  t2.start();
  t2.setName("Consum");
  
 }
 

}


Previous
Next Post »

Pages