java 8新特性 并行流

使用并行流,提高cpu利用率,提高运算速度

   /**
     * java 8并行流
     * 底层运用fork  join框架
     */
    @Test
    public void test(){
        Instant start = Instant.now();

        Long sum=LongStream.rangeClosed(0,100000000L)
                  .parallel()
                  .reduce(0,Long::sum);

        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗时为:"+ Duration.between(start,end).toMillis());;
        //耗时为:141
    }
    
    /**
     * 普通单线程
     */
    @Test
    public void test1(){
        Long sum=0L;
        Instant start = Instant.now();
        for (int i = 0; i <= 100000000L; i++) {
            sum+=i;
        }
        System.out.println(sum);
        Instant end = Instant.now();

        System.out.println("耗时为:"+ Duration.between(start,end).toMillis());;
        //耗时为:648
    }

 

posted @ 2020-04-27 22:29  程程111  阅读(147)  评论(0编辑  收藏  举报