ForkJoinPool线程池--分支执行


import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinPool线程池  分支执行
 * RecursiveAction:没有返回值的任务
 * RecursiveTask:可以携带返回值的任务
 *
 * 数列求和 计算1-200000的和
 */
public class CountTask extends RecursiveTask<Long> {
    private static final int THRESHOLD = 10000;
    private long start;
    private long end;

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

    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end-start)<THRESHOLD;
        if (canCompute){
            for (long i = start; i <= end; i++) {
                sum += i;
            }
        }else {
            //分100组 每组多少个
            long step = (start + end)/100;
            ArrayList<CountTask> tasks = new ArrayList<>();
            // 第一组的第一个
            long pos = start;
            for (int i = 0; i < 100; i++) {
                //每组的最后一个
                long lastOne = pos+step;
                if (lastOne>end) lastOne = end;
                CountTask task = new CountTask(pos,lastOne);
                // 每组的第一个
                pos+=step+1;
                tasks.add(task);
                task.fork();//提交子任务
            }
            // 子任务结果相加
            for (CountTask task : tasks) {
                sum+=task.join();
            }
        }
        return sum;
    }
    public static void main(String[] args){
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask task = new CountTask(0,200000L);
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        try {
            Long res = result.get();//执行get()时,任务没有结束,那么主线程会在get()时等待
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
posted @ 2019-09-05 14:10  fly_bk  阅读(438)  评论(0编辑  收藏  举报