9. ForkJoin

1.大任务化成小任务

2.工作窃取(一个线程已经结束了就去偷其他线程的任务做)

测试类

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();//481
        //test2(); //333
        test3();//352
    }
    public static void test1(){
        long start=System.currentTimeMillis();
        Long sum=0L;
        for (int i = 0; i <=10_0000_0000L ; i++) {
            sum+=i;
        }
        System.out.println(sum);
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }
   
    public static void test2() throws ExecutionException, InterruptedException {
        //forkjoin
        long start=System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> demo = new Demo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(demo);//提交任务
        Long aLong = submit.get();//得到结果
        System.out.println(aLong);
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }

    public static void test3(){
        long start=System.currentTimeMillis();
       //使用stream并行流
        long reduce = LongStream.rangeClosed(0, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end=System.currentTimeMillis();
        System.out.println(reduce);
        System.out.println(end-start);
    }
}

forkjoin

/**
 * @author wuyimin
 * @create 2021-07-09-20:06
 * @description
 * 1. 通过forkJoinPool执行
 * 2. 新建计算任务forkjoinpool.execute(ForkJoinTask task)
 * 3. 计算类继承RecursiveTask 其实就是递归
 */
public class Demo extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    //临界值
    private Long temp=10000L;
    public Demo(Long start,Long end){
        this.start=start;
        this.end=end;
    }
    //计算的方法
    @Override
    protected Long compute() {
        //如果计算量超过临界值就使用分支合并
       if((end-start)<temp){
            Long sum=0L;
           for (int i = 0; i <= end; i++) {
               sum+=i;
           }return sum;
       }else{
           long middle = (start + end) / 2;
           Demo demo = new Demo(start, middle);
           demo.fork();//拆分任务,把任务压入线程队列
           Demo demo1 = new Demo(middle + 1, end);
           demo1.fork();
           return demo.join() + demo1.join();
       }
    }
}

 

posted @ 2021-07-09 21:24  一拳超人的逆袭  阅读(41)  评论(0编辑  收藏  举报