gpt4 book ai didi

java - 在 Java 8 中等待任何 future,而不为每个 future 创建线程

转载 作者:行者123 更新时间:2023-12-02 08:58:13 26 4
gpt4 key购买 nike

我有一个 future 集合,我想等待其中的任何一个,这意味着有一个阻塞调用,一旦任何 future 完成,该调用就会返回。

我看到了CompletableFuture.anyOf(),但是如果我正确理解了它的代码,它会为每个future创建一个线程,如果在Java中可能的话,我想在资源方面使用一种更少浪费的方法.

最佳答案

直接回答是肯定的,这是一个示例方法

    private <T> CompletableFuture<T> waitAny(List<CompletableFuture<T>> allFutures) throws InterruptedException {
Thread thread = Thread.currentThread();
while (!thread.isInterrupted()) {
for (CompletableFuture<T> future : allFutures) {
if (future.isDone()) {
return future;
}
}
Thread.sleep(50L);
}
throw new InterruptedException();
}

第二个选项

    private <T> CompletableFuture<T> waitAny(List<CompletableFuture<T>> allFutures) throws InterruptedException {
CompletableFuture<CompletableFuture<T>> any = new CompletableFuture<>();
for (CompletableFuture<T> future : allFutures) {
future.handleAsync((t, throwable) -> {
any.complete(future);
return null;
});
}
try {
return any.get();
} catch (ExecutionException e) {
throw new IllegalStateException(e);
}
}

但任务的整个背景尚不清楚,可能有更优化的解决方案。

关于java - 在 Java 8 中等待任何 future,而不为每个 future 创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362290/

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