我使用parallelStream來獲取數組中最長的字符串,代碼如下,每次運行時,我都會得到不同的結果。即使在parallelStream中使用時,AtomicReference
是否仍然是線程安全的?但爲什麼會發生?是java的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()最大(Comparator.comparingInt(字符串長度::));'代替。?我試過了,它總是返回相同的單詞。但是,如果它並行執行,我不是100%確定的。 – Clayn
@Clayn:這就是併發問題 - 你永遠無法確定。但我可以斷言你,你的變體是正確的。 – Holger
@Holger感謝您的斷言。我想到的第一件事是:我相信使用Stream API可以做得更加優雅 – Clayn