Java Reference
In-Depth Information
Three concrete blocking queues—
ArrayBlockingQueue
,
LinkedBlockingQueue
,
and
PriorityBlockingQueue
—are provided in Java, as shown in Figure 30.21. All are
in the
java.util.concurrent
package.
ArrayBlockingQueue
implements a block-
ing queue using an array. You have to specify a capacity or an optional fairness to con-
struct an
ArrayBlockingQueue
.
LinkedBlockingQueue
implements a blocking queue
using a linked list. You can create an unbounded or bounded
LinkedBlockingQueue
.
PriorityBlockingQueue
is a priority queue. You can create an unbounded or bounded
priority queue.
«interface»
java.util.concurrent.BlockingQueue<E>
ArrayBlockingQueue<E>
LinkedBlockingQueue<E>
PriorityBlockingQueue<E>
+ArrayBlockingQueue(capacity: int)
+ArrayBlockingQueue(capacity: int,
fair: boolean)
+LinkedBlockingQueue()
+LinkedBlockingQueue(capacity: int)
+PriorityBlockingQueue()
+PriorityBlockingQueue(capacity: int)
F
IGURE
30.21
ArrayBlockingQueue
,
LinkedBlockingQueue
, and
PriorityBlockingQueue
are concrete
blocking queues.
Note
The
put
method will never block an unbounded
LinkedBlockingQueue
or
PriorityBlockingQueue
.
unbounded queue
Listing 30.8 gives an example of using an
ArrayBlockingQueue
to simplify the
Consumer/Producer example in Listing 30.10. Line 5 creates an
ArrayBlockingQueue
to
store integers. The Producer thread puts an integer into the queue (line 22), and the Consumer
thread takes an integer from the queue (line 38).
L
ISTING
30.8
ConsumerProducerUsingBlockingQueue.java
1
import
java.util.concurrent.*;
2
3
public class
ConsumerProducerUsingBlockingQueue {
4
private static
ArrayBlockingQueue<Integer> buffer =
5
new
ArrayBlockingQueue<>(
2
);
create a buffer
6
7
public static void
main(String[] args) {
8
// Create a thread pool with two threads
9 ExecutorService executor = Executors.newFixedThreadPool(
2
);
10 executor.execute(
new
ProducerTask());
11 executor.execute(
new
ConsumerTask());
12 executor.shutdown();
13 }
14
15
// A task for adding an int to the buffer
16
private staticclass
ProducerTask
implements
Runnable {
17
public void
run() {
18
try
{
19
int
i =
1
;
20
while
(
true
) {
21 System.out.println(
"Producer writes "
+ i);
22
create two threads
producer task
buffer.put(i++);
// Add any value to the buffer, say, 1
put
23
// Put the thread into sleep
Search WWH ::
Custom Search