gpt4 book ai didi

java - 从java中的 future 列表中获得第一个完成 future 的方法是什么?

转载 作者:行者123 更新时间:2023-11-29 04:06:16 25 4
gpt4 key购买 nike

以下迭代 future 列表的方式总是等待第一个工作完成:

for (Future<MyFutureResult> future : list) {
List<MyFutureResult> result = future.get();
}

有没有办法先迭代所有完成的工作?

最佳答案

从 futures 列表中获取第一个完成的 Future 是不可能的,因为它们是并行处理的,你必须随时阻塞才能找到结果。

但是您可以通过使用 ExecutorsCompletionService 来控制任务的完成。用于并行处理。此类具有 takepoll 方法,它们返回下一个完成任务的 Future :

A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.

ExecutorService threadPool = Executors.newCachedThreadPool();

CompletionService<Integer> ecs = new ExecutorCompletionService<>(threadPool);

int tasks = 10;

IntStream.range(0, tasks)
.forEach(i -> ecs.submit(() -> i)); // submit tasks

for(int i = 0; i < tasks; i++) {
Future<Integer> take = ecs.take(); // this is blocking operation but futures are returned in completion order. Also you will have to handle InterruptedException
}

// remember to close the ExecutorService after you are done

关于java - 从java中的 future 列表中获得第一个完成 future 的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510690/

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