这里有两个选项,只是有点混淆哪一个最好去。
选项1:
ExecutorService es = Executors.newFixedThreadPool(4);
List<Runnable> tasks = getTasks();
CompletableFuture<?>[] futures = tasks.stream()
.map(task -> CompletableFuture.runAsync(task, es))
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
es.shutdown();
选项2:
ExecutorService es = Executors.newFixedThreadPool(4);
List< Future<?>> futures = new ArrayList<>();
for(Runnable task : taskList) {
futures.add(es.submit(task));
}
for(Future<?> future : futures) {
try {
future.get();
}catch(Exception e){
// do logging and nothing else
}
}
es.shutdown();
这里放下future.get();在尝试捕获是好主意吗?
还有另一种方法可以等待所有任务完成。提交完所有任务后,请致电
es.shutdown()
es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANO_SECONDS)
shutdown [...]启动有序关闭,执行先前提交的任务。
awaitTermination [...]阻塞,直到所有任务在关闭请求之后完成执行,或发生超时,或者当前线程被中断,以先发生者为准。
关于超时:使用上述值,线程池将仅在大约300年后终止。
由于您通过这样做有效地将每个提交的Future
保存在期货列表中:
List< Future<?>> futures = new ArrayList<>();
for(Runnable task : taskList) {
futures.add(es.submit(task));
}
通过调用Future#isDone
方法,您可以非常轻松地检查所有提交的作业是否完成,wilkl根据任务是否完成返回true或false。您可以在相关文档here上查看更多相关信息。
因此,考虑到上述情况,您可以很好地创建一个简单的帮助方法,它将迭代您的期货列表并检查其状态。例如:
private boolean areJobsDone() {
return futures.stream()
.allMatch(Future::isDone);
}
请注意,与Future#get
方法相比,isDone
是非阻塞的(因为它不等待任务返回它的结果),因为它有效地查询它的状态。
有了这个,你可以继续检查你的runnables的状态,在继续之前用一个将调用helper方法的循环阻塞流。
希望这可以帮助。
与Aris_Kortex的提案类似,
List<CompletableFuture<?>> futures = new ArrayList<>();
for(Runnable task : taskList) {
futures.add(CompletableFuture.runAsync(task, es));
}
然后创建组合的CompletableFuture:
CompletableFuture<Void> cf = CompletableFuture.allOf(futures.toArray(futires.size()));
那么你可以同步等待所有任务:
cf.get();
与超时同步:
cf.get(1, TimeUnit.SECOND);
异步的:
cf.thenRun(()->{finalActions();});