gpt4 book ai didi

java - 并发HashMap迭代

转载 作者:行者123 更新时间:2023-12-01 09:52:13 25 4
gpt4 key购买 nike

ConcurrentHashMap是线程安全的,因此我们可以在迭代时更新Map的值。但以下程序的输出并不符合我的预期。

Map concurrentHashMap = new ConcurrentHashMap<();
concurrentHashMap.put("0", "b");
Iterator iterator = concurrentHashMap.entrySet().iterator();
concurrentHashMap.put("8", "k");
concurrentHashMap.put("2", "c");
concurrentHashMap.put("3", "d");
concurrentHashMap.put("1", "e");

while(iterator.hasNext())
{
System.out.println(""+iterator.next());
}

上述代码的输出是

0=b

8=k

3=d

2=c

预期输出

1=e

0=b

8=k

3=d

2=c

最佳答案

来自 ConcurrentHashMap.entrySet() 的文档:

The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

关于java - 并发HashMap迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532943/

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