如何检查ExecutorService上运行的所有任务是否都已完成

我有ConcurrentLinkedDeque,我正在使用同步推/弹元素,我有一些异步任务,从堆栈中取一个元素,如果这个元素有邻居它正在推动它堆栈。

示例代码:

private ConcurrentLinkedDeque 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循环中有另外的声明来回答这个问题 – “Executor中的任何任务都在工作吗?”

如果使用ExecutorService.execute(Runnable)没有一种干净的方法可以检查是否所有Runnable都已完成。 除非你在Runnable本身构建一个机制(在我看来这很草率)。

代替:
使用ExecutorService.submit(Runnable) 。 此方法将返回Future ,它是runnable结果的句柄。 使用Futures提供了一种检查结果的简洁方法。

您所要做的就是维护您提交的期货清单,然后您可以遍历整个期货清单,并且:
A)等待所有期货以阻塞方式完成或
B)检查所有期货是否以非阻塞方式完成。

这是一个代码示例:

 List> futures = new ArrayList>(); ExecutorService exec = Executors.newFixedThreadPool(5); // Instead of using exec.execute() use exec.submit() // because it returns a monitorable future while((item = stack.pollFirst()) != null){ Runnable worker = new Solider(this, item); Future f = exec.submit(worker); futures.add(f); } // A) Await all runnables to be done (blocking) for(Future future : futures) future.get(); // get will block until the future is done // B) Check if all runnables are done (non-blocking) boolean allDone = true; for(Future future : futures){ allDone &= future.isDone(); // check if future is done }