示例
计算一组数据,设置阈值为50,也就是说每次计算的数量不超过50个。
public class RecursiveTaskDemo extends RecursiveTask {
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方法调用。