gpt4 book ai didi

java - Stream 在顺序模式下工作,但在并行模式下有问题

转载 作者:行者123 更新时间:2023-12-01 21:19:37 26 4
gpt4 key购买 nike

目前我正在阅读 Java 8 Lambdas: Pragmatic Functional Programming (非常有趣且写得很好的书,没有广告。)。

第 6 章之后有一个练习:

The code multiplies every number in a list together and multiplies the result by 5. This works fine sequentially, but has a bug when running in parallel.

public static int multiplyThrough(List<Integer> linkedListOfNumbers) {
return linkedListOfNumbers.parallelStream()
.reduce(5, (acc, x) -> x * acc);
}

解决方案:

public static int multiplyThrough(List<Integer> numbers) {
return 5 * numbers.parallelStream()
.reduce(1, (acc, x) -> x * acc);
}

我不明白为什么第一种方法在并行模式下有问题,书中也没有解释。

请解释一下。

最佳答案

javadoc 说:

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t. The accumulator function must be an associative function.

这显然不是您的第一个示例中的情况:

5 * x 不等于 x。

它在并行模式下没有给出相同结果的原因是,在这种模式下,流被分成 block ,并对每个 block 应用减少,然后每个 block 的结果被减少。因此,您最终会乘以 5 多次,而在顺序模式下,乘以 5 只发生一次。

关于java - Stream 在顺序模式下工作,但在并行模式下有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28818618/

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