当多个线程对同一个集合进行增删操作时,就会产生fail-fast 机制
例如:假设存在两个线程(线程1、线程2),线程1通过Iterator在遍历集合A中的元素,在某个时候线程2修改了集合A的结构(是结构上面的修改,而不是简单的修改集合元素的内容),那么这个时候程序就会抛出 ConcurrentModificationException 异常,从而产生fail-fast机制。
原因:迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。集合在被遍历期间如果内容发生变化,就会改变modCount的值。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。
以下代码会产生java.util.ConcurrentModificationException
public static void main(String[] args) throws Exception{
List<String> info = new ArrayList<String>();
for(int i=0;i<10;i++){
info.add(i+"");
}
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("线程一");
for (String str:info) {
System.out.println(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage()+"=============");
e.printStackTrace();
}
}
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("线程二=============");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
info.add("aa");
}
};
new Thread(r1).start();
new Thread(r2).start();
}