Vector
是线程安全的,但在这个实现中它似乎不起作用。使方法同步也无济于事,java.util.ConcurrentModificationException
被抛出。
可以做些什么来解决这个实现呢?
我应该去java.util.concurrent.CopyOnWriteArrayList
吗?
import java.util.Iterator;
import java.util.Vector;
public class VectorExample {
private Vector<Object> v;
public VectorExample() {
v = new Vector<Object>();
}
public void addToVector(Object o) {
v.add(o);
}
public Vector<Object> getV() {
return v;
}
public static void main(String[] args) {
final VectorExample v = new VectorExample();
v.addToVector("obj1");
v.addToVector("obj2");
v.addToVector("obj3");
v.addToVector("obj4");
v.addToVector("obj5");
v.addToVector("obj6");
new Thread(new Runnable() {
@Override
public void run() {
Iterator<Object> it = v.getV().iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
v.addToVector("Obj11");
v.addToVector("Obj12");
v.addToVector("Obj13");
v.addToVector("Obj14");
v.addToVector("Obj15");
v.addToVector("Obj16");
}
}).start();
}
}