保持活动线程的计数。
public class ThreadCounter {
public static final AtomicInteger threadCounter = new AtomicInteger(N);
public static final AtomicInteger queueCounter = new AtomicInteger(0);
public static final Object poisonPill = new Object();
public static volatile boolean cancel = false; // or use a final AomticBoolean instead
}
您的线程的轮询循环应如下所示(我假设您使用的是BlockingQueue)
while(!ThreadCounter.cancel) {
int threadCount = ThreadCounter.threadCounter.decrementAndGet(); // decrement before blocking
if(threadCount == 0 && ThreadCounter.queueCounter.get() == 0) {
ThreadCounter.cancel = true;
queue.offer(ThreadCounter.poisonPill);
} else {
Object obj = queue.take();
ThreadCounter.threadCounter.incrementAndGet(); // increment when the thread is no longer blocking
ThreadCounter.queueCounter.decrementAndGet();
if(obj == ThreadCounter.poisonPill) {
queue.offer(obj); // send the poison pill back through the queue so the other threads can read it
continue;
}
}
}
如果一个线程即将阻塞,BlockingQueue那么它会递减计数器;如果所有线程都已在队列中等待(即counter == 0),则最后一个线程设置cancel为 true,然后通过队列发送毒丸以唤醒其他线程;每个线程看到毒丸,通过队列将其发送回以唤醒剩余线程,然后在看到cancel设置为 true 时退出循环。
编辑:我通过添加一个queueCounter维护队列中对象数量的计数来消除数据竞争(显然,您还需要在queueCounter.incrementAndGet()向队列中添加对象的任何位置添加一个调用)。其工作原理如下: if threadCount == 0, but queueCount != 0,则这意味着线程刚刚从队列中删除了一项但尚未调用threadCount.getAndIncrement,因此取消变量未设置为 true。threadCount.getAndIncrement调用之前调用很重要queueCount.getAndDecrement,否则您仍然会有数据竞争。您调用的顺序无关紧要,queueCount.getAndIncrement因为您不会将其与调用交错threadCount.getAndDecrement(后者将在循环结束时调用,前者将在循环开始时调用)。
请注意,您不能只使用 aqueueCount来确定何时结束进程,因为线程可能仍然处于活动状态而尚未将任何数据放入队列中 - 换句话说,queueCount它将为零,但一旦线程完成了当前的迭代。
poisonPill您可以让取消线程通过队列发送(N-1),而不是通过队列重复发送poisonPills。如果您使用这种方法使用不同的队列请小心,因为某些队列(例如亚马逊的简单队列服务)可能会返回与其take方法等效的多个项目,在这种情况下,您需要重复发送poisonPill以确保所有内容关闭。
此外,while(!cancel)您可以不使用循环,而是使用while(true)循环并在循环检测到poisonPill