根據您的設計,我可以想到下面這樣的事情。 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