ForkJoinPool中submit处理流程

细节不详细介绍,具体可参考http://www.infoq.com/cn/articles/fork-join-introduction。本文主要分析的submit处理流程,示例代码:

package com.company.Chapter06;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


public class CountTask extends RecursiveTask {
    private static final int THEADHOLD = 2;//阈值
    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THEADHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask left = new CountTask(start, middle);
            CountTask right = new CountTask(middle + 1, end);
            left.fork();
            right.fork();
            int leftSum = left.join();
            int rightSum = right.join();
            sum = leftSum + rightSum;
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        CountTask countTask=new CountTask(1,4);
        Future result=forkJoinPool.submit(countTask);
        System.out.println(result.get());
    }
}

submit流程图:

ForkJoinPool中submit处理流程_第1张图片

你可能感兴趣的:(并发,java)