我想计算一个^ b,例如2 ^ 30,
public long pow(final int a, final int b)
Run Code Online (Sandbox Code Playgroud)
首先我用这种方式
return LongStream.range(0, b).reduce(1, (acc, x) -> a * acc); // 1073741824
Run Code Online (Sandbox Code Playgroud)
得到正确的结果.然后我想要平行计算它,所以我自然而然地将它改为
return LongStream.range(0, b).parallel().reduce(1, (acc, x) -> a * acc); // 32
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,结果就是32.为什么?
所以为了支持并行我再次改变它
return Collections.nCopies(b,a).parallelStream().reduce(1, (acc, x) -> acc * x); // 1073741824
Run Code Online (Sandbox Code Playgroud)
在这种情况下它有效.
那方式有什么问题parallel?