我在下面的代码尝试。虽然用一个线程修改ArrayList并用另一个线程迭代它,但它抛出ConcurrentModificationException
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();
}
}
它有时抛出ConcurrentModificationException并且有时会成功运行。
我不明白的是,因为有2个不同的方法,每个包含一个线程。他们将一一执行。当一个线程完成修改列表时,线程2将开始迭代。
我也提到这个链接(Why no ConcurrentModificationException when one thread iterating (using Iterator) and other thread modifying same copy of non-thread-safe ArrayList),但它是不同的情况。
那么,它为什么抛出这个异常?是因为线程吗?
有人可以解释一下吗?
请不要链接到代码/文章。编辑您的问题以包含实际的代码片段。 – Bohemian
@Bohemian:我编辑了这篇文章。 –
应该没有CME:迭代器被创建但没有被使用 – Bohemian