ForkJoinPool
//计算0,100的总和=5050
class MyTask extends RecursiveTask<Integer>{
//声明一些变量
//以10为界限区分!
private static final Integer ADJUST_VALUE = 10;
private int begin;
private int end;
private int result;
//创建一个构造方法
public MyTask(int begin,int end){
this.begin = begin;
this.end = end;
}
//递归调用
@Override
protected Integer compute() {
if ((end-begin)<=ADJUST_VALUE){
for (int i = begin; i <=end; i++) {
result = result+i;
}
}else {
//0,100 相差100 找个中间值 100/2=50 0,50 51,100
int mid = (begin+end)/2;
MyTask myTask01 = new MyTask(begin, mid);
MyTask myTask02 = new MyTask(mid+1, end);
//计算
myTask01.fork();
myTask02.fork();
//最终计算结果
result = myTask01.join()+myTask02.join();
}
return result;
}
}
public class ForkJoinDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyTask myTask = new MyTask(0, 100);
//分支合并池
ForkJoinPool forkJoinPool = new ForkJoinPool();
//需要将ForkJoinTask扔进去
ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
System.out.println(forkJoinTask.get());
}
}