示例:
list.stream().reduce() 单线程 与 list.stream().parallel().reduce()多线程效率比较
package com.yqzl.mybatis.test.thread.demo01;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
/**
* @description:
* @author: YqZhilan
* @date: 2020-07-16
*/
public class StreamDemo3 {
public static void main(String[] args) {
System.out.println(String.format("本计算机的核数: %d", Runtime.getRuntime().availableProcessors()));
Random random = new Random();
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 1000_00000; i++) {
list.add(random.nextInt(100));
}
long prevTime = System.currentTimeMillis();
list.stream().reduce((a, b) -> a + b).ifPresent(System.out::println);
System.out.println(String.format("单线程计算耗时: %d", System.currentTimeMillis() - prevTime));
prevTime = System.currentTimeMillis();
list.stream().parallel().reduce((a, b) -> a + b).ifPresent(System.out::println);
System.out.println(String.format("多线程计算耗时: %d", System.currentTimeMillis() - prevTime));
}
}
返回结果:
本计算机的核数: 6
654754513
单线程计算耗时: 13249
654754513
多线程计算耗时: 251