程序员也分三六九等

本文通过三个不同等级的代码实现计算10亿以内所有数之和,分别是简单的for循环、使用Fork/Join框架和Java 8的Stream API并行处理。实验结果显示,Stream API的并行处理在效率上显著优于传统的循环和Fork/Join框架,分别用时271毫秒和4138毫秒,展示了并行计算的优势。

计算10亿之内所有的数之和:

三等:

   static void test() {
        long starttime = System.currentTimeMillis();
        long sum = 0;
        for (Long i = 0L; i < 1000000000L; i++) {
            sum += i;
        }
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - starttime);// test();//4807

    }

六等:

public class ForkJoinTest extends RecursiveTask<Long> {


    private long start;
    private long end;
    private long temp = 10000L;
    private long sum;

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

    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {
            Long middle = (end + start) / 2;
            ForkJoinTest forkJoinTest = new ForkJoinTest(start, middle);
            forkJoinTest.fork();
            ForkJoinTest forkJoinTest2 = new ForkJoinTest(middle + 1, end);
            forkJoinTest2.fork();

            return forkJoinTest.join() + forkJoinTest2.join();
        }
    }
}

    static void test2() throws ExecutionException, InterruptedException {
        long starttime = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinTest = new ForkJoinTest(0L, 1000000000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
        Long aLong = submit.get();
        long endtime = System.currentTimeMillis();

        System.out.println(endtime - starttime);// test2();//4138

    }

九等:

 static void test3() {
        long starttime = System.currentTimeMillis();
        LongStream.rangeClosed(0L, 1000000000L).parallel().reduce(0, Long::sum);
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - starttime);//test3()//271

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

掉头发的王富贵

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

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

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

打赏作者

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

抵扣说明:

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

余额充值