completableFutureList = new ArrayList<>(); for-6ren">
gpt4 book ai didi

Java CompletableFuture.allOf() 找不到任何数组元素

转载 作者:行者123 更新时间:2023-12-02 10:20:34 26 4
gpt4 key购买 nike

一个非常简单的代码片段如下:

String[] list = {"a", "b", "c"};
List<CompletableFuture<String>> completableFutureList = new ArrayList<>();
for (String s : list) {
completableFutureList.add(CompletableFuture.supplyAsync(() -> s)
.thenApply(String::toUpperCase));
}
CompletableFuture<String>[] a = completableFutureList
.toArray(new CompletableFuture[completableFutureList.size()]);
System.out.println(a.length);
CompletableFuture.allOf(a).whenComplete((r, e) -> {
if (null != r) {
System.out.println(r);
} else {
throw new RuntimeException(e);
}
});

我希望程序应该打印“A B C”。但实际上什么也没打印。为什么以及如何解决这个问题?

最佳答案

引用CompletableFuture.allOf()方法的Javadoc(重点是我的):

Returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. If any of the given CompletableFutures complete exceptionally, then the returned CompletableFuture also does so, with a CompletionException holding this exception as its cause. Otherwise, the results, if any, of the given CompletableFutures are not reflected in the returned CompletableFuture, but may be obtained by inspecting them individually. If no CompletableFutures are provided, returns a CompletableFuture completed with the value {@code null}.

所以我认为您需要在 whenComplete() 回调中手动查询它们(例如使用 a[0].get())。像这样的事情:

CompletableFuture.allOf(a).whenComplete((r, e) -> {
for (CompletableFuture<String> future : a) {
try {
System.out.println(future.get());
}
catch (InterruptedException | ExecutionException e1) {
e1.printStackTrace();
}
}
});

关于Java CompletableFuture.allOf() 找不到任何数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54365047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com