1.1 目标


使用for循环,串行Stream流,并行Stream流来对5亿个数字求和。看消耗的时间。
image.png
image.png

  1. private static final int times = 500000000;
  2. long start;
  3. @Before
  4. public void init() {
  5. start = System.currentTimeMillis();
  6. }
  7. @After
  8. public void destory() {
  9. long end = System.currentTimeMillis();
  10. System.out.println("消耗时间:" + (end - start));
  11. }
  12. // 并行的Stream : 消耗时间:137
  13. @Test
  14. public void testParallelStream() {
  15. LongStream.rangeClosed(0, times).parallel().reduce(0, Long::sum);
  16. }
  17. // 串行的Stream : 消耗时间:343
  18. @Test
  19. public void testStream() {
  20. // 得到5亿个数字,并求和
  21. LongStream.rangeClosed(0, times).reduce(0, Long::sum);
  22. }
  23. // 使用for循环 : 消耗时间:235
  24. @Test
  25. public void testFor() {
  26. int sum = 0;
  27. for (int i = 0; i < times; i++) {
  28. sum += i;
  29. }
  30. }

我们可以看到parallelStream的效率是最高的。

Stream并行处理的过程会分而治之,也就是将一个大任务切分成多个小任务,这表示每个任务都是一个操作。