我想知道使用CompletableFuture接口是否可以代替executorService.invokeAll()
服务。我已经看到许多使用runAsynch()
或supplyAsynch()
的CompletableFuture接口的代码示例,但是我无法理解如何组合所有可调用对象并在CompletableFuture接口中运行它?
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
return "Task 1";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return "Task 2";
}
});
List<Future<String>> futures = executorService.invokeAll(callables);
for(Future<String> future : futures){
System.out.println("future.get = " + future.get());
}
executorService.shutdown();
我希望CompletableFuture的代码版本不同