public class TestForkJoin { public static void main(String[] args) throws ExecutionException, InterruptedException { int[] array = new int[10000]; IntStream.range(0, 10000) .forEach(i -> array[i] = i); System.out.println(Arrays.stream(array).sum()); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask<Long> submit = forkJoinPool.submit(new LongSum(0, array.length, array)); System.out.println(submit.get()); }}
public class LongSum extends RecursiveTask<Long> { static final int SEQUENTIAL_THRESHOLD = 10000; int low; int high; int[] array; public LongSum(int low, int high, int[] array) { this.low = low; this.high = high; this.array = array; } @Override protected Long compute() { if (high - low <= SEQUENTIAL_THRESHOLD) { long sum = 0; for (int i = low; i < high; i++) { sum += array[i]; } return sum; } else { int mid = low + (high - low) / 2; LongSum left = new LongSum(low, mid, array); LongSum right = new LongSum(mid, high, array); left.fork(); right.fork(); Long leftAns = left.join(); Long rightAns = right.join(); return leftAns + rightAns; } }}