【发布时间】:2016-08-31 12:21:22
【问题描述】:
我使用parallelStream来获取数组中最长的字符串,代码如下,每次运行时,我都会得到不同的结果。 AtomicReference 即使在 parallelStream 中使用也应该是线程安全的?但是为什么会这样呢?
public static void main(String[] args) {
AtomicReference<String> longest = new AtomicReference<>();
LongAccumulator accumulator = new LongAccumulator(Math::max, 0);
List<String> words = Arrays.asList("him", "he", "thanks", "strings", "congratulations", "platform");
words.parallelStream().forEach(
next -> longest.updateAndGet(
current -> {
String result = next.length() > accumulator.intValue() ? next : current;
accumulator.accumulate(next.length());
return result;
}
)
);
System.out.println(longest.get());
}
有一次,我会打印“祝贺”,有时会打印“平台”。
【问题讨论】:
-
可以改用
words.parallelStream().max(Comparator.comparingInt(String::length));吗?我试过了,它总是返回相同的词。但是我不能 100% 确定它是否可以并行执行。 -
@Clayn:这就是并发的问题——你永远无法确定。但我可以断言,您的变体是正确的。
-
@Holger 感谢您的断言。我首先想到的是:我确信使用 Stream API 可以做得更优雅