美文网首页
JUC(13) - ForkJoinPool 分支/合并框架 工

JUC(13) - ForkJoinPool 分支/合并框架 工

作者: 21号新秀_邓肯 | 来源:发表于2020-05-18 19:42 被阅读0次

    13. ForkJoinPool 分支/合并框架 工作窃取

    Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总

    Fork/Join 框架
    class ForkJoinSumCalculate extends RecursiveTask<Long> {
    
        private static final long serialVersionUID = -259195479995561737L;
    
        private long start;
    
        private long end;
    
        /**
         * 临界值
         */
        private static final long THRESHOLD = 10000L;
    
        public ForkJoinSumCalculate(long start, long end) {
            this.start = start;
            this.end = end;
        }
    
        @Override
        protected Long compute() {
            long len = end - start;
            if (len <= THRESHOLD) {
                long sum = 0;
    
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            } else {
                long middle = (start + end) / 2;
                ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
                //进行拆分, 同时压入线程队列
                left.fork();
    
                ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle, end);
                //进行拆分, 同时压入线程队列
                right.fork();
    
                return left.join() + right.join();
    
            }
        }
    }
    
    

    测试

        public static void main(String[] args) {
            Instant start = Instant.now();
    
            ForkJoinPool pool = new ForkJoinPool();
    
            ForkJoinSumCalculate task = new ForkJoinSumCalculate(0L, 50000000000L);
    
            Long sum = pool.invoke(task);
    
            System.out.println(sum);
    
            Instant end = Instant.now();
            System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
        }
    

    相关文章

      网友评论

          本文标题:JUC(13) - ForkJoinPool 分支/合并框架 工

          本文链接:https://www.haomeiwen.com/subject/aoucohtx.html