多线程之Fork/Join框架

2019-10-24 02:35:29 浏览数 (1)

Fork/join

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

代码语言:javascript复制
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));

    }
}

0 人点赞