如果使用,没有一种干净的方法来检查所有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 futurewhile((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}


