java之Fork-Join分治编程简单用法
解决方法:
1.循环10000次计算0-10000数字叠加的和
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyRecursiveTask myRecursiveTask = new MyRecursiveTask(0,10000);
ForkJoinPool pool=new ForkJoinPool();
pool.execute(myRecursiveTask);
System.out.println("结果值:"+myRecursiveTask.get());
pool.shutdown();
}
2.MyRecursiveTask 源码:
import java.util.concurrent.RecursiveTask;
public class MyRecursiveTask extends RecursiveTask<Integer>{
private int begin;
private int end;
public MyRecursiveTask(int begin, int end) {
super();
this.begin = begin;
this.end = end;
}
@Override
protected Integer compute() {
if((end-begin)!=0){
int min=(begin+end)/2;
MyRecursiveTask myRecursiveTaskLeft = new MyRecursiveTask(begin,min);
MyRecursiveTask myRecursiveTaskRight = new MyRecursiveTask(min+1,end);
this.invokeAll(myRecursiveTaskLeft,myRecursiveTaskRight);
int left=myRecursiveTaskLeft.join();
int right=myRecursiveTaskRight.join();
return left+right;
}else{
return end
}
}
}
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1503