CountDownLatch是一个线程等待其他的所有线程执行完成。
先对数组进行分段,每段求和,主线程等待所有线程计算完成之后,在执行整体求和。
public class CountDownLatchTest {
CountDownLatchTest(int count) {
this.count = count;
executorService = Executors.newFixedThreadPool(count);
countDownLatch = new CountDownLatch(count);
}
private Map<String, Integer> sumMap = new HashMap<>();
private int count = 4;
private CountDownLatch countDownLatch;
private ExecutorService executorService;
public int sum(int[] arr) {
int size = arr.length;
int batch = size / count + 1;
for (int i = 0; i < count; i++) {
int end;
int start;
start = i * batch;
end = Math.min(start + batch, size);
System.out.println(start + " " + end);
executorService.execute(new Calculator(arr, start, end));
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
return sumMap.values().stream().reduce(Integer::sum).get();
}
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
CountDownLatchTest countDownLatchTest = new CountDownLatchTest(4);
System.out.println(countDownLatchTest.sum(arr));
}
class Calculator implements Runnable {
private int[] arr;
private int start;
private int end;
Calculator(int[] arr, int start, int end) {
this.arr = arr;
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i < end; i++) {
sum += arr[i];
}
sumMap.put(Thread.currentThread().getName(), sum);
countDownLatch.countDown();
}
}
}