java併發編程學習之Fork/Join 框架-RecursiveTask(二)

示例

計算一組數據,設置閾值爲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;
    }
}

運行結果以下:
clipboard.png
能夠看出,兩次結果是同樣的。ide

步驟

  1. 建立ForkJoinPool對象。
  2. 建立繼承RecursiveTask的類,實現compute方法,這裏主要是計算以及拆分任務、合併結果。
  3. pool.invoke方法調用。
相關文章
相關標籤/搜索