1. public class TestForkJoin {
    2. public static void main(String[] args) throws ExecutionException, InterruptedException {
    3. int[] array = new int[10000];
    4. IntStream.range(0, 10000)
    5. .forEach(i -> array[i] = i);
    6. System.out.println(Arrays.stream(array).sum());
    7. ForkJoinPool forkJoinPool = new ForkJoinPool();
    8. ForkJoinTask<Long> submit = forkJoinPool.submit(new LongSum(0, array.length, array));
    9. System.out.println(submit.get());
    10. }
    11. }
    1. public class LongSum extends RecursiveTask<Long> {
    2. static final int SEQUENTIAL_THRESHOLD = 10000;
    3. int low;
    4. int high;
    5. int[] array;
    6. public LongSum(int low, int high, int[] array) {
    7. this.low = low;
    8. this.high = high;
    9. this.array = array;
    10. }
    11. @Override
    12. protected Long compute() {
    13. if (high - low <= SEQUENTIAL_THRESHOLD) {
    14. long sum = 0;
    15. for (int i = low; i < high; i++) {
    16. sum += array[i];
    17. }
    18. return sum;
    19. } else {
    20. int mid = low + (high - low) / 2;
    21. LongSum left = new LongSum(low, mid, array);
    22. LongSum right = new LongSum(mid, high, array);
    23. left.fork();
    24. right.fork();
    25. Long leftAns = left.join();
    26. Long rightAns = right.join();
    27. return leftAns + rightAns;
    28. }
    29. }
    30. }