根据您的设计,我可以想到下面这样的事情。 ConsumerTask可以使用泛型,但我很难弄清楚如何在Producer线程中执行相同的操作。生产者和消费者都对生产/消费的物品数量有限制。从TimerTask逻辑中取消timerTask本身的run()方法中的定时器对于它的停止至关重要。在这种情况下,只能使用毒药丸方法来关闭。 如果使用Executors.newSingleThreadExecutor()或scheduledThreadPoolExecutor(),则可以使用shutdown()和shutdownNow()方法来停止生产者或使用者。虽然TimerTask是检查ConcurrentQueue的工作的一个很好的例子,但它不会用于生产系统。
编辑 向生产者线程添加通用功能。构造函数现在使用一个模板类来实现将项目添加到队列的方法。我定义了一个抽象类AddItem,它包含和addItem()方法,只要生产者想将项添加到队列中,该方法就会被调用。
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class ConsumerTask<T> extends TimerTask {
Timer timer;
ConcurrentLinkedQueue<T> itemQueue;
AtomicLong count = new AtomicLong(0);
final long limit;
public ConsumerTask(ConcurrentLinkedQueue<T> itemQ, long lim, int seconds) {
limit = lim;
timer = new Timer();
timer.scheduleAtFixedRate(this, new Date(), seconds * 1000);
itemQueue = itemQ;
}
public void run() {
T item = itemQueue.peek();
if (item != null) {
if (count.incrementAndGet() <= limit) {
System.out.println("Extracting Item : " + itemQueue.poll());
} else {
System.out
.println("Consumed : " + (count.get() - 1) + " items");
timer.cancel();
}
}
}
public static void main(String args[]) throws InterruptedException {
ConcurrentLinkedQueue<Integer> itemQ = new ConcurrentLinkedQueue<Integer>();
ConsumerTask<Integer> ct = new ConsumerTask<Integer>(itemQ, 10, 1);
new Thread(new Producer<Integer>(itemQ, new IntegerAddItem(itemQ), 20))
.start();
new Thread(ct).start();
}
}
abstract class AddItem<T> {
ConcurrentLinkedQueue<T> itemQ;
T t;
public AddItem(ConcurrentLinkedQueue<T> itemQ) {
this.itemQ = itemQ;
}
abstract boolean addItem();
public boolean addItem(T t) {
return itemQ.add(t);
}
}
class IntegerAddItem extends AddItem<Integer> {
public IntegerAddItem(ConcurrentLinkedQueue<Integer> itemQ) {
super(itemQ);
}
AtomicInteger item = new AtomicInteger(0);
@Override
boolean addItem() {
return addItem(item.incrementAndGet());
}
}
class Producer<T> implements Runnable {
private final ConcurrentLinkedQueue<T> itemQueue;
AtomicInteger item = new AtomicInteger(0);
AtomicLong count = new AtomicLong(0);
AddItem<T> addMethod;
final long limit;
public Producer(ConcurrentLinkedQueue<T> itemQ, AddItem<T> addMethod,
long limit) {
itemQueue = itemQ;
this.limit = limit;
this.addMethod = addMethod;
}
public void run() {
while (count.getAndIncrement() < limit) {
addMethod.addItem();
try {
Thread.sleep(new Random().nextInt(5000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Thread.currentThread().interrupt();
}
}
}
}
你有多个消费者吗? –
@Akram Berkawy:只有一个消费者 – Michael