我有一个ConcurrentLinkedDeque,用于同步推入/弹出元素,并且我有一些异步任务,它们从堆栈中取出一个元素,如果该元素具有邻居,则将其推入堆栈。
示例代码:
private ConcurrentLinkedDeque<Item> stack = new ConcurrentLinkedDeque<>();
private ExecutorService exec = Executors.newFixedThreadPool(5);
while ((item = stack.pollFirst()) != null) {
if (item == null) {
} else {
Runnable worker = new Solider(this, item);
exec.execute(worker);
}
}
class Solider{
public void run(){
if(item.hasNeighbors){
for(Item item:item.neighbors){
stack.push(item)
}
}
}
}
我希望在while循环中添加额外的语句来回答这个问题 - "执行器中是否有任何任务正在运行?"
allDone
的目的是通过使用&=
运算符来获取一个单一的布尔值,指示 所有 futures 是否已完成。future.isDone()
只能用于检查单个 Future 是否已完成。 - Andy Guibertexec.Shutdown();
和exec.awaitTermination(...);
的好处是什么? - Michael Ziluckfuture.get()
会使当前线程休眠,并在结果可用时得到通知。 - Andy Guibert