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

查看:16
本文介绍了为什么并行流在 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.

一种是遇到顺序,它定义在流文档.考虑这一点的一个好方法是源集合中元素的空间从左到右顺序.如果源是 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.

还有 processingtemporal 顺序,文档中没有定义,而是不同线程处理元素的时间顺序.如果列表的元素由不同的线程并行处理,则线程可能会先处理列表中最右侧的元素,然后再处理最左侧的元素.但下一次可能不会.

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天全站免登陆