計算一組數據,設置閾值爲50,也就是說每次計算的數量不超過50個。dom
public class RecursiveTaskDemo extends RecursiveTask<Integer> { private static final int MAX = 50; private int[] arr; private int start; private int end; public RecursiveTaskDemo(int[] arr, int start, int end) { this.arr = arr; this.start = start; this.end = end; } @Override protected Integer compute() { if ((end - start) < MAX) { int sum = 0; for (int i = start; i <= end; i++) { sum += arr[i]; } return sum; } else { int mid = (end + start) / 2; RecursiveTaskDemo left = new RecursiveTaskDemo(arr, start, mid); RecursiveTaskDemo right = new RecursiveTaskDemo(arr, mid + 1, end); invokeAll(left, right); return left.join() + right.join(); } } public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); int[] randomArr = getRandomArr(1000); RecursiveTaskDemo task = new RecursiveTaskDemo(randomArr, 0, randomArr.length - 1); System.out.println("總數1=" + pool.invoke(task)); System.out.println("總數2=" + Arrays.stream(randomArr).parallel().sum()); } public static int[] getRandomArr(int num) { int[] arr = new int[num]; for (int i = 0; i < arr.length; i++) { arr[i] = new Random().nextInt(1000); } return arr; } }
運行結果以下:
能夠看出,兩次結果是同樣的。ide