问题描述
我正在寻找最好的方法,在 Java 中,异步运行一些计算一些值的任务,当它们全部收集起来时,对它们运行一些进一步的计算。
我以为我走对了这条路
var f1 = CompletableFuture.supplyAsync(() -> Service.findplayers(filter,maxCount,leaderboardType.Unranked));
var f2 = CompletableFuture.supplyAsync(() -> Service.findplayers(filter,leaderboardType._1x1_RM));
var f3 = CompletableFuture.supplyAsync(() -> Service.findplayers(filter,leaderboardType.TG_RM));
var x = CompletableFuture.allOf(f1,f2,f3);
直到我意识到不幸的是 allOf()
没有返回包含 f1
、f2
和 f3
结果的列表而是 void
吗?有什么替代方法吗?否则我必须将结果存储在某种“全局变量”中,然后从 when()
调用中访问它们,这完全违背了使用 supplyAync
与 runAsync
的整个目的,我猜。
解决方法
你做<tr>
<th class="l t colhd" rowspan="11"> 9494Q </th>
<th class="l t colhd" rowspan="3">PBS </th>
<th class="l t colhd">FEB2021</th>
</tr>
,就像你现在做的一样,但也CompletableFuture::allOf
它:
join
然后你做:
CompletableFuture.allOf(f1,f2,f3).join();
以上操作没有加入,因为功能已经完成。
编辑
如果您不想阻止:
Stream.of(f1,f3)
.map(CompletableFuture::join)
.....