java—如何在对map.entryset进行迭代时避免concurrentmodificationexception

ki1q1bka  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(428)

我有以下代码:

static final Map<String, String> map = Collections.synchronizedMap(new HashMap());

    public static void main(String[] args) throws InterruptedException {
        map.put("1", "1");
        map.put("2", "2");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                    System.out.println("after iterator");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();

        Thread.sleep(50);
        map.remove("1");
        System.out.println("removed");
    }

它产生 java.util.ConcurrentModificationException 我怎样才能避免呢?

nimxete2

nimxete21#

除非使用迭代器,否则在迭代集合时不能从集合中移除元素。使用iterator.remove()方法

gz5pxeao

gz5pxeao2#

如果你想迭代 Collections.synchronizedMap 必须显式同步迭代:

synchronized (map) {
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                System.out.println("after iterator");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
         }
vdgimpew

vdgimpew3#

你可以用 static final Map<String, String> map = new ConcurrentHashMap<>(); ```
static final Map<String, String> map = new ConcurrentHashMap<>();

public static void main(String[] args) throws InterruptedException {
map.put("1", "1");
map.put("2", "2");
new Thread(new Runnable() {
@Override
public void run() {
for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
System.out.println("after iterator");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

        }
    }
}).start();

Thread.sleep(50);
map.remove("1");
System.out.println("removed");

}

相关问题