import java.util.concurrent.RecursiveTask; public class MyTask extends RecursiveTask<Integer> { //定义拆分差值 private static final Integer 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)<=VALUE) { // 计算 for (int i=begin;i<=end;i++){ result=result+i; } }else{ int middle=(begin+end)/2; MyTask m1=new MyTask(begin,middle); MyTask m2=new MyTask(middle+1,end); m1.fork(); m2.fork(); result=m1.join()+m2.join(); } return result; } }
public static void main(String[] args) throws ExecutionException, InterruptedException { //创建任务对象 MyTask myTask = new MyTask(0, 100); //创建分支合并池对象 ForkJoinPool pool = new ForkJoinPool(); //执行任务 ForkJoinTask<Integer> forkJoinTask = pool.submit(myTask); //获取执行结果 Integer result = forkJoinTask.get(); //打印结果 System.out.println(result); //关闭池对象 pool.shutdown(); }