Multithreading 当用一个线程修改ArrayList并用另一个线程迭代它时,它抛出ConcurrentModificationException

Multithreading 当用一个线程修改ArrayList并用另一个线程迭代它时,它抛出ConcurrentModificationException,multithreading,iterator,concurrentmodification,Multithreading,Iterator,Concurrentmodification,我试着用下面的代码 public class IteratorFailFastTest { private List<Integer> list = new ArrayList<>(); public IteratorFailFastTest() { for (int i = 0; i < 10; i++) { list.add(i); } } public void ru

我试着用下面的代码

public class IteratorFailFastTest {

    private List<Integer> list = new ArrayList<>();

    public IteratorFailFastTest() {
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
    }

    public void runUpdateThread() {
        Thread thread2 = new Thread(new Runnable() {

            public void run() {
                for (int i = 10; i < 20; i++) {
                    list.add(i);

                }
            }
        });

        thread2.start();
    }


    public void runIteratorThread() {
        Thread thread1 = new Thread(new Runnable() {

            public void run() {
                ListIterator<Integer> iterator = list.listIterator();

                while (iterator.hasNext()) {
                Integer number = iterator.next();
                System.out.println(number);
                }

            }
        });

        thread1.start();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        IteratorFailFastTest tester = new IteratorFailFastTest();

        tester.runIteratorThread();
        tester.runUpdateThread();
    }

}
公共类迭代器FailFastTest{
私有列表=新的ArrayList();
公共迭代器FailFastTest(){
对于(int i=0;i<10;i++){
列表.添加(i);
}
}
public void runUpdateThread(){
Thread thread2=新线程(new Runnable(){
公开募捐{
对于(int i=10;i<20;i++){
列表.添加(i);
}
}
});
thread2.start();
}
public void runiteratorhread(){
Thread thread1=新线程(new Runnable(){
公开募捐{
ListIterator迭代器=list.ListIterator();
while(iterator.hasNext()){
整数=迭代器.next();
系统输出打印项次(编号);
}
}
});
thread1.start();
}
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
迭代器FailFastTest tester=新迭代器FailFastTest();
runIteratorThread();
runUpdateThread();
}
}
它有时抛出ConcurrentModificationException,有时成功运行

我不明白的是,因为有两个不同的方法,每个方法都包含一个线程。他们将一个接一个地执行。当一个线程完成修改列表时,线程2将开始迭代

我也提到了这个link(),但它是不同的场景

那么,它为什么抛出这个异常呢?是因为线程吗


有人能解释一下吗?

您正在启动两个线程,然后不再执行进一步的同步

有时,两个线程将同时运行,您将获得CME。其他时候,第一个线程将在第二个线程实际开始执行之前完成。在这种情况下,我们不会得到CME

得到这种变化的原因很可能是系统负载之类的因素。或者,这可能只是因为线程调度程序是不确定的


与创建/启动线程的开销相比,线程实际上只做很少的工作。因此,它们中的一个可以很快从其
run()
方法返回也就不足为奇了。

请不要链接到代码/文章。编辑你的问题以包含实际的代码片段。@Bohemian:我已经编辑了这篇文章。不应该有CME:迭代器已经创建,但没有used@Bohemian这是我的错。已经添加了迭代器代码。如果我像“Thread obj=new Thread()”那样调用它们,就会出现这种情况;obj.start();螺纹obj2=新螺纹();obj2.start();'但这是两种不同的方法。他们将一个接一个地被叫来。是吗?是的。他们是。但是请仔细阅读
start()
的javadocs。它们不能保证在
start()
调用返回调用方时子线程将运行,事实上,两个
start()
调用使用不同的方法并不重要。