//同时执行多个任务,并等待执行完毕后,将多个任务的返回值合并返回
CompletableFuture<List<Integer>> future1 = CompletableFuture.supplyAsync(() -> Lists.newArrayList(1));
CompletableFuture<List<Integer>> future2 = CompletableFuture.supplyAsync(() -> Lists.newArrayList(2,1));
CompletableFuture<List<Integer>> future3 = CompletableFuture.supplyAsync(() -> Lists.newArrayList(3));
ArrayList<CompletableFuture<List<Integer>>> completableFutures = Lists.newArrayList(future1, future2, future3);
CompletableFuture<List<Integer>> listCompletableFuture1 = CompletableFuture
.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]))
.thenApply(v -> completableFutures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
)
.thenApply(lists -> lists.stream().flatMap(Collection::stream).collect(Collectors.toList()));
List<Integer> join = listCompletableFuture1.join();
System.out.println(join);
CompletableFuture同时执行多个任务合并返回
最新推荐文章于 2025-06-24 14:06:15 发布
本文介绍了如何使用Java的CompletableFuture实现并发任务的执行,并通过`.allOf()`方法等待所有任务完成,最后将结果合并到一个列表中。
2309

被折叠的 条评论
为什么被折叠?



