Java Fork/Join 实战

问:如何充分利用多核 CPU 计算很大 List 中所有整数的和?

答:这个题目的答案其实有好几种解法,CyclicBarrier 或者 java8 的并行流都可以,但是这里使用 Fork/Join 来解答。

/**
 * 答案有删减优化,原文出处(网络ID:since1986)
 * https://juejin.im/post/59be875e5188257e6b6d91c1
 * 如有侵权联系小编删文处理,谢谢
 */
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 future = forkJoinPool.submit(task);
        System.out.println("计算结果为:"+future.get());
        forkJoinPool.shutdown();
    }

    static class CountSumTask extends RecursiveTask {
        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();
            }
        }
    }
}

本文参考自 Fork/Join 实战相关的一道面试题解析

你可能感兴趣的:(Java Fork/Join 实战)