JAVA并发编程3

JAVA并发编程3

ForkJoin

并行执行任务,提高效率。双端队列,可以工作窃取。

在这里插入图片描述

代码

常规相加
private static void normalAdd() {
    long sum = 0L;
    long start = System.currentTimeMillis();
    for (long i = 1L; i <= 10_0000_0000L; i++) {
        sum += i;
    }
    long end = System.currentTimeMillis();
    System.out.println("sum =" + sum + " cost " + (end - start));
}
forkjoin相加
private static void forkJoin() throws ExecutionException, InterruptedException {
    long start = System.currentTimeMillis();
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    ForkJoinBean forkJoinBean = new ForkJoinBean(0L, 10_0000_0000L);
    ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinBean);
    Long sum = submit.get();
    long end = System.currentTimeMillis();
    System.out.println("sum =" + sum + " cost " + (end - start));
}
public class ForkJoinBean extends RecursiveTask<Long> {
    private long start;
    private long end;

    private static final long THRESHOLD = 10000L;

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


    @Override
    protected Long compute() {
        if ((end - start) < THRESHOLD) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long mid = (end + start) / 2;
            ForkJoinBean upTask = new ForkJoinBean(start, mid);
            upTask.fork();
            ForkJoinBean downTask = new ForkJoinBean(mid + 1, end);
            downTask.fork();
            return upTask.join() + downTask.join();
        }
    }
}
流相加
private static void streamJoin() {
    long start = System.currentTimeMillis();
    long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);
    long end = System.currentTimeMillis();
    System.out.println("sum =" + sum + " cost " + (end - start));
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值