我必须创建一个方法来计算数组中所有元素的总和。需要注意的是,数组被分成多个部分,供多个线程同时计算这些部分,然后组合起来计算总和
所有这些都仅限于方法代码内部。问题是当我写:
Thread t = new Thread(()->{
int sum=0;
//do some calculations
//time to pass this result back to the main method
});
本地匿名类只能访问 main 方法的 Final 或有效 Final 局部变量,这意味着我无法创建局部变量然后更改它以更新结果。我想不出一种方法将线程的结果传回以与其他线程的结果相结合。
有什么办法可以解决这个问题吗?
最佳答案
您可以在主线程中划分工作并执行以下操作:
public class Foo implements Runnable {
private volatile CustomArray<Integer> arr;
private volatile Integer sum;
public Foo(CustomArray<Integer> arr) {
this.arr = arr;
}
@Override
public void run() {
synchronized(this.arr) {
sum = arr.getSum();
}
}
public Integer getValue() {
synchronized(this.arr) {
return sum;
}
}
}
并从另一个线程调用,如下所示:
CustomArray<Integer> completeArray = new CustomArray<>(data);
ArrayList<CustomArray<Integer>> dividedArrays = completeArray.divideWork();
for(CustomArray<Integer> each : dividedArrays) {
Foo foo = new Foo(each);
new Thread(foo).start();
// ... join through some method
Integer value = foo.getValue();
}
或者,您可以使用 Executor
和一个Callable
:
public void test() throws InterruptedException, ExecutionException
{
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() {
return 2;
}
};
Future<Integer> future = executor.submit(callable);
// returns 2 or raises an exception if the thread dies
Integer output = future.get();
executor.shutdown();
}
关于Java:线程之间的通信仅限于一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48919408/