Java: 线程之间的通信仅限于一个方法
Java: Communication between threads restricted to a method
我必须创建一个方法来计算数组中所有元素的总和。需要注意的是,数组被分成若干部分供多个线程同时计算这些部分,然后合并计算总和
所有这些都限制在方法代码内部。问题是当我写:
Thread t = new Thread(()->{
int sum=0;
//do some calculations
//time to pass this result back to the main method
});
局部匿名class只能访问main方法的final或effectively 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
and a 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();
}
我必须创建一个方法来计算数组中所有元素的总和。需要注意的是,数组被分成若干部分供多个线程同时计算这些部分,然后合并计算总和
所有这些都限制在方法代码内部。问题是当我写:
Thread t = new Thread(()->{
int sum=0;
//do some calculations
//time to pass this result back to the main method
});
局部匿名class只能访问main方法的final或effectively 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
and a 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();
}