示例
计算一组数据,设置阈值为 50,也就是说每次计算的数量不超过 50 个。
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;
}
}
运行结果如下:
可以看出,两次结果是一样的。
步骤
- 创建 ForkJoinPool 对象。
- 创建继承 RecursiveTask 的类,实现 compute 方法,这里主要是计算以及拆分任务、合并结果。
- pool.invoke 方法调用。