java.util.ConcurrentModificationException
程序员文章站
2022-06-23 12:50:46
...
出现这个异常的情况有很多种
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<Model> vector = new Vector<>();
Vector<Model> 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<Model> 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 List的remove方法导致的异常java.util.ConcurrentModificationException
-
java.util.ConcurrentModificationException详解
-
java.util.ConcurrentModificationException
-
Caused by: java.util.ConcurrentModificationException
-
java.util.ConcurrentModificationException
-
java.util.ConcurrentModificationException: null
-
解决--java.util.ConcurrentModificationException
-
java.util.ConcurrentModificationException 解决方法
-
今天碰到 java.util.ConcurrentModificationException 异常
-
今天碰到 java.util.ConcurrentModificationException 异常