gpt4 book ai didi

java - 如何迭代 Future 对象?

转载 作者:行者123 更新时间:2023-11-30 06:52:17 25 4
gpt4 key购买 nike

我的call()的返回值方法List<Person> 。 MyCallable 类如下所示:

public class MyCallable implements Callable<List<Person>> {

public List<Person> call() throws Exception {

...

return list;
}

public MyCallable(List<Account> accountList) {
super();
}
}

下面是我在 CallableFuture 类中编写的代码:

ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<List<Person>>> list = new ArrayList<Future<List<Person>>>();
for (int i = 0; i < 20; i++) {
Callable<List<Person>> worker = new MyCallable(accountList);
Future<List<Person>> submit = executor.submit(worker);
for(Future<List<Person>> :list){
//list.add(submit);
}
}

我不知道如何迭代list并添加submit到它。我这样做对吗?

最佳答案

有几个问题。首先,不要在提交每个结果后立即尝试获取 Future 的结果(如果这样做,您实际上只是序列化所有内容并达不到目的),而是提交 all 其中,然后检索结果:

List<Future<List<Person>>> list = new ArrayList<Future<List<Person>>>();
for (int i = 0; i < 20; i++) {
Callable<List<Person>> worker = new MyCallable(accountList);
Future<List<Person>> submit = executor.submit(worker);
list.add(submit); // just keep track of them
}

// NOW the next step is to get the results...

接下来,您将遇到一些基本的语法问题。一般来说,迭代容器中的项目的语法是:

List<A> list = ...;

for (A a : list) {
// do things with 'a'
}

最后,您需要检查 Future 的文档,它向您展示了如何等待计算并使用 Future#get() 获取结果。

将所有这些放在一起,您最终会得到下一步(在提交上述所有内容之后):

// ... all tasks submitted and 'list' now contains the Futures, next step:

for (Future<List<Person>> future : list) {
List<Person> result = future.get(); // wait for task to complete
// 'result' is now the List<Person> returned from the corresponding callable.
}

提交所有内容然后获取所有结果背后的想法是,您现在允许任务同时执行,而不是等待每个任务完成后再添加下一个任务。然后,最后,即使您最终等待了一些任务,也没关系,因为所有任务的总等待时间已按预期减少。

关于java - 如何迭代 Future<List> 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197169/

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