gpt4 book ai didi

java - Java 中的并行线程

转载 作者:行者123 更新时间:2023-11-29 03:59:26 26 4
gpt4 key购买 nike

好的,所以我正在尝试查找二维数组的最大元素。我将有一个方法接受 2darray 作为参数并找到最大值。它需要找到每一行的最大元素作为一个单独的线程,以便线程并行运行,然后加入每个线程,并找到其中的最大值以获得整个二维数组的最大值。现在我遇到的问题是 run() 不返回任何值...那么我应该如何访问已修改的值。例如

public static int maxof2darray(long[][] input){


ArrayList<Thread> threads = new ArrayList<Thread>();
long[]rowArray;
for(int i=0; i<input.length; i++){
rowArray = input[i];
teste r1 = new teste(rowArray,max);
threads.add(new Thread(r1));
}

for ( Thread x : threads )
{
x.start();

}
try {


for ( Thread x : threads)
{
x.join();
}
}

如您所见,它创建了一个线程对象数组列表。然后获取每一行并调用找到该行最大值的 run() 函数...问题是 run() 不返回任何值...那么我怎么可能访问该行的最大值?

最佳答案

Future API应该做你需要的。

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.

关于java - Java 中的并行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4407115/

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