ConcurrentHashMap是线程安全的,所以我们可以在迭代时更新映射的值.但以下程序的输出并不像我预期的那样。
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
发布于 2016-08-19 14:41:53
来自ConcurrentHashMap.entrySet()的文档
视图的迭代器是一个“弱一致性”迭代器,它永远不会抛出
ConcurrentModificationException,并保证遍历元素,因为它们在构建迭代器时就存在,并且可以(但不能保证)反映构造后的任何修改。
https://stackoverflow.com/questions/37532943
复制相似问题