java.util.ConcurrentModificationException

出现这个异常的情况有很多种

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.Vector$Itr.checkForComodification(Vector.java:1184)
    at java.util.Vector$Itr.next(Vector.java:1137)
    at com.example.MyClass.test(MyClass.java:106)
    at com.example.MyClass.main(MyClass.java:10)

下面是出异常的源代码

    public static void test() {

        Vector vector = new Vector<>();
        Vector vector1 = new Vector<>();

        for (int i = 0; i < 50; i++) {
            Model model = new Model();
            model.setName("item" + i);
            vector1.add(model);
            vector.add(vector1.get(i));
        }

        Thread thread = new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                if (i % 2 == 0) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    vector.remove(vector1.get(i));
                    System.out.println(Thread.currentThread().getName() + "<------------->" + vector1.get(i).getName());
                }
            }
        });
        thread.setName("thread-test");
        thread.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Model model : vector) {  //出现异常的位置
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(vector.size() + "<------------->" + model.getName());
        }
    }

因为foreach遍历集合的原理是通过Iterator迭代器实现遍历的,和以下代码类似

    Iterator iterator = vector.iterator();
    while (iterator.hasNext()){
        Model model = iterator.next();
        System.out.println(vector.size() + "<------------->" + model.getName());
    }

这里的iterator在一开始就拿到了,而后又通过thread-test线程删除了vector的某个元素,所以会出现java.util.ConcurrentModificationException

解决方法

使用fori循环就可以解决这个问题了

    for (int i = 0; i < vector.size(); i++) {
        Model model = vector.get(i);
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(vector.size() + "<------------->" + model.getName());
    }

运行看下效果:
java.util.ConcurrentModificationException_第1张图片

你可能感兴趣的:(笔记)