为什么并行流在Java 8中按顺序收集 [英] Why parallel stream get collected sequentially in Java 8

查看:635
本文介绍了为什么并行流在Java 8中按顺序收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 forEach 以随机顺序打印数字,而 collect 始终按原始顺序收集元素,即使是并行流也是如此?

Why forEach prints numbers in random order, while collect always collects elements in original order, even from parallel stream?

Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));

System.out.println("Parallel Stream: ");
listOfIntegers
  .stream()
  .parallel()
  .forEach(e -> System.out.print(e + " "));
System.out.println();

// Collectors         
List<Integer> l = listOfIntegers
  .stream()
  .parallel()
  .collect(Collectors.toList());
System.out.println(l);

输出:

Parallel Stream: 
8 1 6 2 7 4 5 3 
[1, 2, 3, 4, 5, 6, 7, 8]


推荐答案

这里有两种不同的排序,这使讨论变得混乱。

There are two different kinds of "ordering" going on here, which makes the discussion confusing.

一种是遭遇订单,它在streams文档。考虑这一点的一个好方法是源集合中元素的空间从左到右顺序。如果源是 List ,请考虑前面元素左侧的早期元素。

One kind is encounter order, which is defined in the streams documentation. A good way to think about this is the spatial or left-to-right order of elements in the source collection. If the source is a List, consider the earlier elements being to the left of later elements.

还有处理时间顺序,它未在文档中定义,但是不同线程处理元素的时间顺序。如果列表的元素由不同的线程并行处理,则线程可以在最左边的元素之前处理列表中最右边的元素。但是下一次它可能没有。

There is also processing or temporal order, which isn't defined in the documentation, but which is the time order in which elements are processed by different threads. If the elements of a list are being processed in parallel by different threads, a thread might process the rightmost element in the list before the leftmost element. But the next time it might not.

即使计算是并行完成的,大多数收集器和一些终端操作经过仔细安排,以便它们保持从源到目的地的遭遇订单,而不管时间顺序,其中不同的线程可能处理每个元素。

Even when computations are done in parallel, most Collectors and some terminal operations are carefully arranged so that they preserve encounter order from the source through to the destination, independently of the temporal order in which different threads might process each element.

请注意 forEach 终端操作保留遭遇顺序。相反,它由任何产生下一个结果的线程运行。如果您想要保留遭遇订单的 forEach ,请改为使用 forEachOrdered

Note that the forEach terminal operation does not preserve encounter order. Instead, it's run by whatever thread happens to produce the next result. If you want something like forEach that preserves encounter order, use forEachOrdered instead.

另请参阅 Lambda常见问题解答有关订购问题的进一步讨论。

See also the Lambda FAQ for further discussion about ordering issues.

这篇关于为什么并行流在Java 8中按顺序收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆