Java8 串行流和并行流效率对比

Java8 串行流和并行流效率对比,第1张

Java8 串行流和并行流效率对比

哈哈,废话不多说,上菜:


public class LamdbaExpress01 {
    public static void main(String[] args) {
        testStream();
        testParallelStream();

    }

    public static void testStream(){
        long startStream = System.currentTimeMillis();
        long sumStream = LongStream.rangeClosed(0, 2000000).sum();
        System.out.println("串行流总和:"+sumStream);
        long endStream = System.currentTimeMillis();
        System.out.println("总耗费时间:"+(endStream-startStream));
    }

    public static void testParallelStream(){
        long startTime = System.currentTimeMillis();
        long sumStream = LongStream.rangeClosed(0, 2000000).parallel().sum();
        System.out.println("并行流总和:"+sumStream);
        long endTime = System.currentTimeMillis();
        System.out.println("总耗费时间:"+(endTime-startTime));
    }
}

输出结果:

串行流总和:2000001000000
总耗费时间:156
并行流总和:2000001000000
总耗费时间:16

很显然,并行流节约了很多时间。对并行流的底层实现感兴趣的同学可以去看看。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5575278.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存