并发修改异常 (ConcurrntModificationException)原理及其解决方案
问题演示
小伙伴们可以运行一下
遍历集合元素的过程中删除元素
public void testConcurrentModifyException() throws InterruptedException {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
for(Integer num : list){
list.remove(0);
}
}
第二种方式
1.创建10个线程分别共享变量ArrayList添加元素,
2.主线程对ArrayList进行遍历
运行过程中就会抛出ConcurrentModificationException
public void testConcurrentModifyException() throws InterruptedException {
List<Integer> list = new ArrayList<>();
for(int i = 0;i < 10;i++){
new Thread(()-> {
for(int j = 0;j < 100;j++) {
list.add(j);
}