Java并发修改异常ConcurrentModificationException

我们先看下面的代码

public class Demo {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if (next.equals("C")) {
                list.add("D");
            }
            System.out.println("next: "+next);
        }
    }
}

上面的代码会抛出

java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at Demo.main(Demo.java:25)

你可能感兴趣的:(Java并发修改异常ConcurrentModificationException)