【JUC】Fork / Join split and merge

Branch merge example

/**
 * 计算1+2+3...+100 , 拆分成多任务计算,最后汇总,拆分标准是最大最小值差值不超过10
 * 如果任务比较耗时,明显多线程拆分要快得多
 */
class  MyTask extends RecursiveTask<Integer> {
    
    

    //拆分最大最小差值不超过10
    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() {
    
    
        //判断相加的两个数差值是否大于10
        if((end - begin) <= VALUE) {
    
    
            //相加操作
            for(int i = begin; i <= end; i++) {
    
    
                result += i;
                try {
    
    
                    TimeUnit.MICROSECONDS.sleep(100);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }else {
    
    
            //进一步拆分
            //二分拆分
            int mid = (begin + end) / 2;
            //拆分左边
            MyTask task01 = new MyTask(begin, mid);;
            //拆分右边
            MyTask task02 = new MyTask(mid + 1, end);
            //调用方法拆分
            task01.fork();
            task02.fork();
            //合并结果
            result = task01.join() + task02.join();
        }
        return result;
    }
}


public class ForkJoinDemo {
    
    
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    

        long start = System.currentTimeMillis();
        //创建MyTask对象
        MyTask myTask = new MyTask(0,100);

        //创建分钟合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);

        //获取最终合并之后的结果
        Integer result = forkJoinTask.get();
        System.out.println("result = " + result);

        //关闭池对象
        forkJoinPool.shutdown();
        long end = System.currentTimeMillis();
        System.out.println("花费时间:" + (end - start));

        int sum = 0;
        for (int i = 0; i <= 100; i++) {
    
    
            sum += i;
            TimeUnit.MICROSECONDS.sleep(100);
        }
        System.out.println("sum = " + sum);
        long end2 = System.currentTimeMillis();
        System.out.println("花费时间:" + (end2 - end));
    }
}

Guess you like

Origin blog.csdn.net/weixin_44179010/article/details/123411363