gpt4 book ai didi

Java 流 : difference between forEach and forEachOrdered

转载 作者:行者123 更新时间:2023-12-03 22:55:28 24 4
gpt4 key购买 nike

前提:我已经读过this question和其他人,但我需要一些说明。

我理解 Stream.forEach 方法在处理并行流时(不仅)有所不同,这解释了为什么这样做

//1
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.forEachOrdered(item -> System.out.print(item));

打印

one two three four five six

但是当涉及到中间操作时,流并行化时不再保证顺序。所以这段代码

//2
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.peek(item -> System.out.print(item))
.forEachOrdered(item -> System.out.print(""));

会打印类似的东西

four six five one three two 

forEachOrdered 方法只影响其自身执行中的元素顺序是否正确?直觉上,我认为 //1 示例与

完全相同
//3
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.peek(item -> System.out.print("")) //or any other intermediate operation
.sequential()
.forEach(item -> System.out.print(item));

我的直觉错了吗?我是否遗漏了有关整个机制的某些信息?

最佳答案

您是对的,为 forEachOrdered 的操作所做的保证仅适用于该操作,而不适用于其他操作。但是假设这与 .sequential().forEach(...) 相同是错误的。

sequential 会将整个流管道变成顺序模式,因此,传递给 forEach 的 Action 将由同一个线程执行,而且前面的 peek 的 Action 。对于大多数中间操作,parallelsequential 的确切位置是无关紧要的,同时指定两者是没有意义的,因为只有最后一个是相关的。

此外,在使用 forEach 时仍然没有关于顺序的保证,即使它在当前实现中没有任何影响。这在 “Does Stream.forEach respect the encounter order of sequential streams?” 中讨论

documentation of Stream.forEachOrdered状态:

This operation processes the elements one at a time, in encounter order if one exists. Performing the action for one element happens-before performing the action for subsequent elements, but for any given element, the action may be performed in whatever thread the library chooses.

因此,操作可能会被不同的线程调用,正如 Thread.currentThread() 所感知的那样,但不会同时运行。此外,如果流有遭遇顺序,它将在此处重新构成。 This answer阐明了遇到顺序处理顺序的区别。

关于Java 流 : difference between forEach and forEachOrdered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com