将线程的结果相加:
import java.util.concurrent.*;
public class ThreadExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
int[] array = new int[1000];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int sum = 0;
for (int i = 0; i < 10; i++) {
int start = i * 100;
int end = start + 100;
Future future = executorService.submit(new AddThread(array, start, end));
sum += future.get();
}
System.out.println("Sum: " + sum);
executorService.shutdown();
}
}
class AddThread implements Callable {
private int[] array;
private int start;
private int end;
public AddThread(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
}
}