gpt4 book ai didi

java - 为什么 Vector 会出现 ConcurrentModificationException?

转载 作者:太空宇宙 更新时间:2023-11-04 11:43:27 24 4
gpt4 key购买 nike

这是我的测试:

public static List<String> list =new Vector<String>();
@Test
public void main(){
new ThreadOne().start();
new ThreadTwo().start();
}
public static void printAll(){
String valueString= null;
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
valueString = (String) iterator.next();
System.out.print(valueString+",");
}
System.out.println("\n");
}
public static class ThreadOne extends Thread{
public void run(){
int i=10;
while(i<100000){
list.add(String.valueOf(i));
printAll();
i++;
}
}

}
public static class ThreadTwo extends Thread{
public void run(){
int i=0;
while(i<100000){
list.add(String.valueOf(i));
printAll();
i++;

}
}

}

我在 Vector.class 中看到了有关迭代器的源代码:

 public synchronized Iterator<E> iterator() {
return new Itr();
}

/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;

public boolean hasNext() {
// Racy but within spec, since modifications are checked
// within or after synchronization in next/previous
return cursor != elementCount;
}

public E next() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor;
if (i >= elementCount)
throw new NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}

我对此很困惑。当程序执行iterator.next()时, vector 对象被锁定,当程序执行list.add()时, vector 也被锁定。变量“expectedModCount”始终等于“modCount”。为什么会出现ConcurrentModificationException?

最佳答案

迭代器的下一个方法是同步的。这意味着它在读取每个元素后释放锁,然后在读取后续元素时获取锁。在调用 next 之间仍然有机会更改 vector 的内容,从而触发 ConcurrentModificationException。

关于java - 为什么 Vector 会出现 ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42569893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com