Java Reference
In-Depth Information
The
TransferQueue
has two more methods to get more information about the waiting consumers. The
getWaitingConsumerCount()
method returns the number of waiting consumers. The
hasWaitingConsumer()
method
returns
true
if there is a waiting consumer; otherwise, it returns
false
.
The
LinkedTransferQueue
is an implementation class for the
TransferQueue interface
. It provides an
unbounded
TransferQueue
. It is based on
FIFO
. That is, the element that enters the
TransferQueue
first is removed
from the queue first.
Listing 12-26 contains code for a
TQProducer
class whose instance represents a producer for a
TransferQueue
.
The producer sleeps for a random number of seconds between 1 and 5. It generates an integer. If the integer is even, it
puts it in the queue. If the integer is odd, it tries to hand it off to a consumer using the
transfer()
method. Note that
if the
TransferQueue
has some elements, the consumer will consume those elements first, before it consumes the
element that a producer is trying to hand off using the
transfer()
method.
Listing 12-26.
A TQProducer Class That Represents a Producer for a TransferQueue
// TQProducer.java
package com.jdojo.collections;
import java.util.Random;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class TQProducer extends Thread {
private final String name;
private final TransferQueue<Integer> tQueue;
private final AtomicInteger sequence;
private Random rand = new Random();
public TQProducer(String name, TransferQueue<Integer> tQueue, AtomicInteger sequence) {
this.name = name;
this.tQueue = tQueue;
this.sequence = sequence;
}
@Override
public void run() {
while (true) {
try {
// Sleep for 1 tp 5 random number of seconds
int sleepTime = rand.nextInt(5) + 1;
Thread.sleep(sleepTime * 1000);
// Generate a sequence number
int nextNum = this.sequence.incrementAndGet();
// An even number is enqueued. An odd number is handed off
// to a consumer
if (nextNum % 2 == 0) {
System.out.format("%s: Enqueuing: %d%n", name, nextNum);
tQueue.put(nextNum); // Enqueue
}