码上敲享录 > java高并发常见问题 > java之Fork-Join分治编程简单用法

java之Fork-Join分治编程简单用法

上一章章节目录下一章 2018-08-19已有1468人阅读 评论(0)

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


0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交