Java Reference
In-Depth Information
Listing 12-23 creates a bounded and fair blocking queue. It creates one producer and two consumers. Each
producer/consumer is created in a separate thread. A partial output has been shown. You will have to stop the
application manually. You may experiment with adding more producers or consumers and adjusting their sleep
times. Note that the messages printed in the output may not appear in the order that makes sense; this is typical in a
multi-threaded program. A thread performs an action and it is preempted before it can print a message stating that it
did perform the action. Meanwhile, you will see messages from another thread.
Listing 12-23. A Class to Run the Producer/Consumer Program
// BQProducerConsumerTest.java
package com.jdojo.collections;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
public class BQProducerConsumerTest {
public static void main(String[] args) {
int capacity = 5;
boolean fair = true;
BlockingQueue<String> queue = new ArrayBlockingQueue<>(capacity, fair);
// Create one producer and two consumer and let them produce
// and consume indefinitely
new BQProducer(queue, "Producer1").start();
new BQConsumer(queue, "Consumer1").start();
new BQConsumer(queue, "Consumer2").start();
}
}
Consumer1 is trying to take an element. Remaining capacity: 5
Consumer2 is trying to take an element. Remaining capacity: 5
Producer1 is trying to add: Producer1-1. Remaining capacity: 5
Producer1 added: Producer1-1
Consumer1 took: Producer1-1
Producer1 is trying to add: Producer1-2. Remaining capacity: 5
Producer1 added: Producer1-2
Consumer2 took: Producer1-2
Consumer1 is trying to take an element. Remaining capacity: 5
Consumer2 is trying to take an element. Remaining capacity: 5
...
I will not discuss an example of PriorityBlockingQueue . You can use the PriorityBlockingQueue
implementation class to create the blocking queue in Listing 12-23 and the same example will work. Note that a
PriorityBlockingQueue is an unbounded queue. You may also want to use a different type of element (other than
a string), which will emulate the priority of elements in a better way. Please refer to Listing 12-17 for an example of a
simple non-blocking priority queue.
 
Search WWH ::




Custom Search