【JUC编程进阶】ForkJoin分支合并

并行执行任务,提高效率。把大任务拆分城小任务。分开执行,最后结果汇总。
特点:工作窃取
维护的是 双端队列


package forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName Test.java
 * @Description TODO
 * @createTime 2021年06月01日 19:31:00
 */
public class Test {
    public static void main(String[] args) throws Exception{
        test1();
        test2();
        test3();
    }
    public  static void test1(){
        long sum = 0;
        long start = System.currentTimeMillis();
        for (int i = 0; i <= 1000000000; i++) {
            sum = sum + i;
        }

        long end = System.currentTimeMillis();
        System.out.println("sum"+sum+" 时间"+(end-start));
    }
    public  static void test2()throws Exception{
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new demo1(0,1000000000);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);

        long end = System.currentTimeMillis();
        System.out.println("sum"+submit.get()+"时间"+(end-start));
    }
    public  static void test3(){
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0,1000000000).parallel().reduce(0,Long::sum);


        long end = System.currentTimeMillis();
        System.out.println("sum"+sum+"时间"+(end-start));
    }
}

package forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName demo1.java
 * @Description TODO
 * @createTime 2021年06月01日 19:14:00
 */
public class demo1 extends RecursiveTask<Long> {

    private long start;
    private long end;

    // 临界值
    private long temp = 10000L;

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


  // 计算方法
    @Override
    protected Long compute() {
        if ((end-start)<temp){
            long sum = 0;
            for (long i = start;i<=end;i++){
                sum = sum + i;
            }
            return sum;
        }else
        {
            long middle = (start+end)/2;   // 中间值
            demo1 task1 = new demo1(start,middle);
            task1.fork();  // 拆分任务,把任务压入线程队列
            demo1 task2 = new demo1(middle+1,end);
            task2.fork();
            return task1.join()+task2.join();


        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr_树先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值