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


问题内容

我有ConcurrentLinkedDeque,它用于同步push /
pop元素,还有一些异步任务,这些任务正在从堆栈中获取一个元素,如果该元素具有邻居,则会将其推入堆栈。

示例代码:

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循环中有另外一条语句来回答问题-“执行程序中的任何任务都在工作?”


问题答案:

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

相反:
使用ExecutorService.submit(Runnable)。此方法将返回a
Future<?>,它是a的结果的句柄Runnable。使用期货提供了一种检查结果的干净方法。

您要做的只是维护您提交的期货列表,然后可以遍历整个期货列表,然后:
A)等待所有期货以封闭方式完成,或者
B)检查是否所有期货以非阻塞方式进行。

这是一个代码示例:

List<Future<?>> futures = new ArrayList<Future<?>>();
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
}