Problem statement : There are n Thread , n/2 thread are producer and n/2 are consumer, number produced by producer-1 thread must be consumed by consumer-1 thread. Thread must also run in order, producer 1, then consumer 1, again producer 2 and then consumer 2…so on…..
I am implementing producer consumer in java using thread but requirement is that there are N/2 producer thread and N/2 Consumer Thread, N consumer thread should consume value produce by N producer and n-1 consumer thread should consume by n-1 producer value.
I have implementing this using blocking queue but not getting the desire output :
package paytm;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerWithBlockingQueue {
public static class Producer implements Runnable {
private BlockingQueue<Integer> queue;
private int next = 0;
private String thereadName;
public Producer(BlockingQueue<Integer> queue,String threadName) {
this.queue = queue;
this.thereadName = threadName;
}
@Override
public void run() {
while (true) {
try {
if(next<10) {
queue.put(next);
System.out.println(thereadName+ " "+ next);
}
} catch (InterruptedException e) {
}
next++;
}
}
}
public static class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
private String thereadName;
public Consumer(BlockingQueue<Integer> queue,String threadName) {
this.queue = queue;
this.thereadName = threadName;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
Integer next;
try {
next = queue.take();
System.out.println(thereadName+ " "+ next);
} catch (InterruptedException e) {
}
}
}
}
}
public static void main(String args[]) throws Exception {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(1);
Thread producer1 = new Thread(new Producer(queue,"producer1"));
Thread producer2 = new Thread(new Producer(queue,"producer2"));
Thread consumer1 = new Thread(new Consumer(queue,"Consumer1"));
Thread consumer2 = new Thread(new Consumer(queue,"Consumer2"));
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
// producer1.join();
// producer2.join();
// consumer1.join();
// consumer2.join();
}
}
// Output :
producer1 0
consumer1 0
producer2 1
consumer2 1
producer3 2
consumer3 2 so on...