美文网首页
多线程之Fork/Join框架

多线程之Fork/Join框架

作者: OPice | 来源:发表于2019-09-23 13:06 被阅读0次

    Fork/join

    并行执行任务的框架,将任务拆成若干子任务,汇总每个子任务计算的结果。

    public class SumTask extends RecursiveTask<Long> {
    
        private int start;
        private int end;
        private int[] arr;
        private int threshold = 5;
    
        public SumTask(int start, int end, int[] arr) {
            this.start = start;
            this.end = end;
            this.arr = arr;
        }
    
        @Override
        protected Long compute() {
    
            if(end - start > threshold) {
                int mid = (start + end) / 2;
                SumTask subTask1 = new SumTask(start, mid, arr);
                SumTask subTask2 = new SumTask(mid, end, arr);
                invokeAll(subTask1, subTask2); //fork
                long subResult1 = subTask1.join();
                long subResult2 = subTask2.join();
                System.out.println(String.format("compute %d~%d = %d", start, end, subResult1 + subResult2));
                return subResult1 + subResult2;
    
            } else {
                long sum = 0;
                for(int i = start; i < end; i++) {
                    sum += arr[i];
                }
                System.out.println(String.format("compute %d~%d = %d", start, end, sum));
                return sum;
            }
    
        }
    
        public static void main(String[] args) {
    
            int[] arr = new int[100];
            for(int i = 0; i < 100; i++) {
                arr[i] = i;
            }
    
            ForkJoinPool pool = new ForkJoinPool(4);//最大并发数
            ForkJoinTask<Long> task = new SumTask(0, 100, arr);
            System.out.println("result:" + pool.invoke(task));
    
        }
    }
    

    相关文章

      网友评论

          本文标题:多线程之Fork/Join框架

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