問:如何充分利用多核 CPU 計算很大 List 中所有整數(shù)的和?
答:這個題目的答案其實有好幾種解法,CyclicBarrier 或者 java8 的并行流都可以,但是這里使用 Fork/Join 來解答。
/**
* 答案有刪減優(yōu)化,原文出處(網(wǎng)絡(luò)ID:since1986)
* https://juejin.im/post/59be875e5188257e6b6d91c1
* 如有侵權(quán)聯(lián)系小編刪文處理,謝謝
*/
public class ForkJoinLargeListSum {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int[] array = IntStream.rangeClosed(0, 10000000).toArray();
ForkJoinPool forkJoinPool = new ForkJoinPool();
CountSumTask task = new CountSumTask(0, array.length, 10000, array);
Future<Integer> future = forkJoinPool.submit(task);
System.out.println("計算結(jié)果為:"+future.get());
forkJoinPool.shutdown();
}
static class CountSumTask extends RecursiveTask<Integer> {
private int high, low;
private int threshold;
private int[] array;
CountSumTask(int low, int high, int threshold, int[] array) {
this.array = array;
this.low = low;
this.high = high;
this.threshold = threshold;
}
@Override
protected Integer compute() {
if (high - low <= threshold) {
int sum = 0;
for (int i = low; i < high; i++) {
sum += array[i];
}
return sum;
} else {
int middle = (high - low) / 2 + low;
CountSumTask leftHandTask = new CountSumTask(low, middle, threshold, array);
CountSumTask rightHandTask = new CountSumTask(middle, high, threshold, array);
leftHandTask.fork();
rightHandTask.fork();
return leftHandTask.join() + rightHandTask.join();
}
}
}
}