qq_15622913 2016-08-05 03:24 采纳率: 0%
浏览 853
已结题

同步容器为什么会出现不安全情况???

public class Test {
static Vector vector = new Vector();
public static void main(String[] args) throws InterruptedException {
while(true) {
for(int i=0;i vector.add(i);
Thread thread1 = new Thread(){
public void run() {
for(int i=0;i vector.remove(i);
};
};
Thread thread2 = new Thread(){
public void run() {
for(int i=0;i vector.get(i);
};
};
thread1.start();
thread2.start();
while(Thread.activeCount()>10) {

        }
    }
}

}

  • 写回答

1条回答 默认 最新

  • 鱼弦 优质创作者: 编程框架技术领域 2016-08-05 03:52
    关注

    容器里的数值和地址是变化的,remove或者add之后,你在get会发生位置偏移,获取的会出错,不安全

    评论

报告相同问题?