gpt4 book ai didi

java集合synchronizedMap不工作

转载 作者:行者123 更新时间:2023-12-02 04:14:59 24 4
gpt4 key购买 nike

当我多次运行下面的代码时,下面的代码给出 ConcurrentModificationException 。当我使用非concurrentHashMap时它工作正常。

    public static void main(String[] args) {

Map<String, String> stringSyncedMap = Collections.synchronizedMap(new HashMap<String, String>());

CollectionJob collectionJob1 = new CollectionJob(stringSyncedMap, "read");
CollectionJob collectionJob2 = new CollectionJob(stringSyncedMap, "write");

Thread thread1 = new Thread(collectionJob1, "T1");
Thread thread2 = new Thread(collectionJob2, "T2");

thread1.start();
thread2.start();
}

}

public class CollectionJob implements Runnable {

private Map<String, String> stringCollection;
private String operation;

public CollectionJob(Map<String, String> stringCollection, String operation) {

this.stringCollection = stringCollection;
this.operation = operation;
}

public void run() {

if (operation.equals("read"))
readFromCollection();
else
writeToCollection();

System.out.println("done");

}

public void writeToCollection() {
for (int i = 10; i < 20; i++) {
stringCollection.put("String " + i, "String"+i);

}

public void readFromCollection() {
for (String str : stringCollection.keySet())
System.out.println(str);
}
}

我缺少什么。

最佳答案

ConcurrentHashMap 不同,当通过 Collections.synchronizedMap 惯用法初始化时,您需要显式同步 Map,例如使用synchronized关键字。

来自docs :

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views: [...]

关于java集合synchronizedMap不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33412583/

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