Home >Java >javaTutorial >Introduction and usage of Fork/Join appearing in java7
The Fork/Join that appears in JAVA7 is similar to the mapreduce idea of the distributed file system hadoop, which is to divide the task and then divide it until the conditions are met
In order to facilitate understanding: programming logic can borrow the idea of recursion, recurse layer by layer until the final call is encountered, and then return layer by layer; in Fork/Join, it is similar to placing each recursive method in a separate thread. Medium;
Make full use of modern multi-core processors to process tasks in parallel
Such as:
/** * 继承RecursiveTask 则每个子任务带返回值 * 继承RecursiveAction 则每个子任务不带返回值 */public class FockJoin1 extends RecursiveTask<Integer>{public static void main(String[] args) throws ExecutionException, InterruptedException {long l = System.currentTimeMillis(); ForkJoinPool pool = new ForkJoinPool(); //类似线程池,也实现了AbstractExecutorServiceFockJoin1 task = new FockJoin1(1,1000000000); //新建任务Future<Integer> 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; } @Overrideprotected 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; } }
The above is the detailed content of Introduction and usage of Fork/Join appearing in java7. For more information, please follow other related articles on the PHP Chinese website!