Reputation: 576
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...
Upvotes: 0
Views: 116
Reputation: 393
This might not do what you expect it to do:
while (true)
synchronized(queue) {
...
}
}
Let's suppose that consumer1
wins the race and gets in to the synchronized
block while consumer2
is forced to wait. What do you suppose will happen when consumer1
does its thing, and then exits from the synchronized
block?
The Java Language Specification does not say what must happen in that case, but in most implementations, what actually will happen is, consumer1
will go right back into the synchronized
block before consumer2
even starts to wake up.
Intrinsic locks in Java are not fair.
Upvotes: 1