Fork/Join
JAVA7中出现的Fork/Join,类似于分布式文件系统hadoop的mapreduce思想,就是将任务分割,再分割,直到分割到满足条件
为了便于理解:编程逻辑可以借用 递归的思想,层层递归,直到碰到最终调件,然后层层返回;而在Fork/Join中就是,类似把每个递归的方法,单独的放到一个线程中;
充分利用现代多核处理器,对任务进行并行处理
如:
/** * 继承RecursiveTask 则每个子任务带返回值 * 继承RecursiveAction 则每个子任务不带返回值 */public class FockJoin1 extends RecursiveTask{ public static void main(String[] args) throws ExecutionException, InterruptedException { long l = System.currentTimeMillis(); ForkJoinPool pool = new ForkJoinPool(); //类似线程池,也实现了AbstractExecutorService FockJoin1 task = new FockJoin1(1,1000000000); //新建任务 Future result = pool.submit(task); //将任务提交 System.out.println("result is" + result.get()); //获取结果 System.err.println(System.currentTimeMillis() - l); } private final Integer index = 5000; //分割任务的基数 private final Integer left; private final Integer right; public FockJoin1(Integer left, Integer right) { this.left = left; this.right = right; } @Override protected Integer compute() { int sum = 0; if(right - left < index) { //如果任务 小于基数,则直接执行;类似递归的出口 for (int i = left; i <= right; i++) { sum += i; } }else { //任务 大于基数,则分割,类似与二分法,也可以更多 int middle = (right + left) >> 1; FockJoin1 myf1 = new FockJoin1(left, middle); //二分法左边 FockJoin1 myf2= new FockJoin1(middle+1, right); //二分法右边 myf1.fork(); //继续执行,类似递归 myf2.fork(); //继续执行,类似递归 Integer integer1 = myf1.join(); //等待 Integer integer2 = myf2.join(); sum = integer1 + integer2; //结果合并 } return sum; }}