原文:When to Use a Parallel Stream in Java
Streams in Java
顺序流 Sequential Stream
默认,Java中的任何流操作都是顺序执行的,除非特别指定为并行。
顺序流是单线程执行的:
List<Integer> listOfNumbers = Arrays.asList(1,2,3,4);
listOfNumbers.stream().forEach(number ->
System.out.println(number + " " + Thread.currentThread().getName()));
执行结果:
1 main
2 main
3 main
4 main
并行流 Parallel Stream
Java中任何流都可以从顺序流转为并行流。通过添加parallel
方法到一个顺序流或者调用parallelStream
方法直接创建一个并行流。
List<Integer> listOfNumbers = Arrays.asList(1,2,3,4);
listOfNumbers.