這是否使從Vector的安全迭代 ConcurrentModificationException?
是它使從ConcurrentModificationException
安全的迭代過向量。如果它不是在這種情況下再同步的,如果你是通過不同的線程訪問Vector和在任何其他線程在結構上修改矢量迭代器創建後的迭代器會拋出ConcurrentModificationException
。 考慮在運行此代碼:
import java.util.*;
class VVector
{
static Vector<Integer> mapItems = new Vector<Integer>();
static
{
for (int i = 0 ; i < 200 ; i++)
{
mapItems.add(i);
}
}
public static void readVector()
{
Iterator<Integer> iterator = mapItems.iterator();
try
{
while(iterator.hasNext())
{
System.out.print(iterator.next() + "\t");
}
}
catch (Exception ex){ex.printStackTrace();System.exit(0);}
}
public static void main(String[] args)
{
VVector v = new VVector();
Thread th = new Thread(new Runnable()
{
public void run()
{
int counter = 0;
while (true)
{
mapItems.add(345);
counter++;
if (counter == 100)
{
break;
}
}
}
});
th.start();
v.readVector();
}
}
在我的系統中,它顯示下面的輸出,同時執行:
0 1 2 3 4 5 6 7 8 9
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at VVector.readVector(VVector.java:19)
at VVector.main(VVector.java:38)
但在另一方面,如果你做的含Iterator
訪問Vector
代碼塊同步使用mapItems
作爲鎖,它將阻止執行與Vector
相關的其他方法,直到塊完全原子化。
你有任何正確的答案接受?? – AmitG 2013-04-05 07:15:22