我正在努力实现这样的目标。这是一个表达意图的虚构示例。
我希望所有可完成的 future 都执行并将其所有结果合并为一个结果并返回该结果。因此,对于下面的示例,集合 allResults 应该包含字符串“一”、“二”、“三”,每个字符串 3 次。我希望它们都并行而不是串行运行。
任何指向我可以用来实现这一目标的可完成 future 的 API 的指针都会非常有帮助。
public class Main {
public static void main(String[] args) {
int x = 3;
List<String> allResuts;
for (int i = 0; i < x; i++) {
//call getCompletableFutureResult() and combine all the results
}
}
public static CompletableFuture<List<String>> getCompletableFutureResult() {
return CompletableFuture.supplyAsync(() -> getResult());
}
private static List<String> getResult() {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
return list;
}
}
最佳答案
Venkata Raju 的回答有问题。拉朱用过 获取 call on future 这是一个阻塞调用,它扼杀了异步风格编码的主要目的。始终避免做 future 。
有大量内置方法围绕处理 future 值而构建,例如 thenApply、thenAccept、thenCompose、thenCombine 等。CompletableFuture.allOf
方法是在您必须处理多个 future 时使用。
它有以下签名
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
旁注:
CompletableFuture.anyOf
当你只关心第一个 future 完成时可以使用。使用 allOf
当您需要完成所有 future 时。我将使用 CompletableFuture.allOf 以下列方式编码您的规范。
public class DorjeeTest {
public static CompletableFuture<List<String>> getCompetableFutureResult() {
return CompletableFuture.supplyAsync(() -> getResult());
}
public static List<String> getResult() {
return Lists.newArrayList("one", "two", "three");
}
public static void testFutures() {
int x = 3;
List<CompletableFuture<List<String>>> futureResultList = Lists.newArrayList();
for (int i = 0; i < x; i++) {
futureResultList.add(getCompetableFutureResult());
}
CompletableFuture[] futureResultArray = futureResultList.toArray(new CompletableFuture[futureResultList.size()]);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray);
CompletableFuture<List<List<String>>> finalResults = combinedFuture
.thenApply(voidd ->
futureResultList.stream()
.map(future -> future.join())
.collect(Collectors.toList()));
finalResults.thenAccept(result -> System.out.println(result));
}
public static void main(String[] args) {
testFutures();
System.out.println("put debug break point on this line...");
}
}
关于java - 如何在循环中调用可完成的 future 并组合所有结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46589510/