gpt4 book ai didi

java - 如何在多个线程中收集方法的返回值

转载 作者:行者123 更新时间:2023-11-30 08:12:05 26 4
gpt4 key购买 nike

我正在为列表中的每个对象启动一个新线程,并在这些对象上调用一个方法。我调用的方法返回一个我想保存的值:

public int[] benchAll(){
int[] numbers = new int[things.size()];
for (final Thing thing: things) {
final Generator generator = new Generator();

new Thread(
() -> generator.benchmark(thing)
).start();
generators.add(generator);
}
return numbers;
}

现在如何将 benchmark() 的每个返回值保存在其他线程中,以便使用此方法 benchAll() 返回它?

非常感谢您的帮助。

最佳答案

使用 java.util.concurrent.ExecutorService 正如 Java 规范所说:

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

因此,使用 ExecutorService 的实现,您可以在给定数量的线程中异步或同步运行所有任务。为此,您需要创建一个 Callable 对象列表,并将其传递给 ExecutorService 对象的 invokeAll 方法。invokeAll 方法将返回 Future 对象列表的列表(每个 Future 对象将代表每个任务,顺序与您在 Callable 传递给 invokeAll< 的列表中的顺序相同 方法),你可以循环计算任务的所有结果并打印出来。

您应该阅读 Executors 类的所有可用方法,这些方法返回 ExecutorService 的不同实例,因此选择适合您的方法。

通过这种方式,您将能够在 M 个线程中异步运行 N 个任务,一旦所有线程都完成,您将获得 Future 对象的列表,它将为您提供每个任务的完成信息/状态。
您可以将该结果与其他结果/数据合并并从您的方法返回。

检查下面的伪示例:

try {
List<Callable<Object>> callableList = new ArrayList<Callable<Object>>();
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/

//Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService
final ExecutorService service = Executors.newFixedThreadPool(3);

//This will invoke all your N tasks in specified M threads ...
List<Future<String[]>> futureObjects = service.invokeAll(callableList); //futureObjects will contain result of each thread execution
} catch (InterruptedException e) {
e.printStackTrace();
}

关于java - 如何在多个线程中收集方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30711491/

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