Multiple producer/consumer example with shared global queue
suggest changeThe code below shows a program with multiple producers and consumers. The producer and consumer threads share one global queue.
import java.util.concurrent.*;
import java.util.Random;
public class ProducerConsumerWithES {
public static void main(String args[]) {
BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();
ExecutorService pes = Executors.newFixedThreadPool(2);
ExecutorService ces = Executors.newFixedThreadPool(2);
pes.submit(new Producer(sharedQueue, 1));
pes.submit(new Producer(sharedQueue, 2));
ces.submit(new Consumer(sharedQueue, 1));
ces.submit(new Consumer(sharedQueue, 2));
pes.shutdown();
try {
pes.awaitTermination(5, TimeUnit.SECONDS);
sharedQueue.put(Producer.DONE);
sharedQueue.put(Producer.DONE);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
}
ces.shutdown();
}
}
/* Different producers produces a stream of integers continuously to a shared queue,
which is shared between all Producers and consumers */
class Producer implements Runnable {
static final int DONE = -1;
private final BlockingQueue<Integer> sharedQueue;
private final int threadNo;
private final Random random = new Random();
public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) {
this.threadNo = threadNo;
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
// Produce a finite batch so the example terminates cleanly.
for (int i = 0; i < 5; i++) {
try {
int number = random.nextInt(1000);
System.out.println("Produced:" + number + ":by thread:"+ threadNo);
sharedQueue.put(number);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return;
}
}
}
}
/* Different consumers consume data from shared queue, which is shared by both producer and consumer threads */
class Consumer implements Runnable {
private final BlockingQueue<Integer> sharedQueue;
private final int threadNo;
public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) {
this.sharedQueue = sharedQueue;
this.threadNo = threadNo;
}
@Override
public void run() {
while (true) {
try {
int num = sharedQueue.take();
if (num == Producer.DONE) {
return;
}
System.out.println("Consumed: "+ num + ":by thread:"+threadNo);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return;
}
}
}
}
Produced:69:by thread:2
Produced:553:by thread:1
Consumed: 69:by thread:1
Consumed: 553:by thread:2
Produced:41:by thread:2
Produced:796:by thread:1
Consumed: 41:by thread:1
Consumed: 796:by thread:2
Produced:728:by thread:2
Consumed: 728:by thread:1
The trace above is one possible interleaving of the random values, not a complete run.
Explanation:
sharedQueue, aLinkedBlockingQueue, is shared by all producer and consumer threads.- Each producer puts five random integers on
sharedQueue. There is no delay between those puts. The main thread then puts twoDONEmarkers so both consumers can stop. - Each consumer takes integers from
sharedQueueuntil it takesDONE. - This program is implemented without explicit
synchronizedorLockconstructs. BlockingQueue is the key to that.
BlockingQueue implementations are designed to be used primarily for producer-consumer queues.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents