对照视频写了这部分代码, 但是我的没出现数组下标月结的错误啊?
来源:5-6 同步容器-1
![](http://img1.sycdn.imooc.com/user/5458643d0001a93c02200220-100-100.jpg)
慕沐3161652
2018-07-08
对照视频写了这部分代码, 但是我的没出现数组下标月结的错误啊?
我的代码如下:
```java
/**
* 演示Vector 同步容器线程不安全的情况
*/
@NotThreadSafe
@Slf4j
public class VectorExample2 {
private static List<Integer> vector = new Vector<>();
public static void main(String[] args) {
while (true) {
for (int i = 0; i < 10; i++) {
vector.add(i);
}
Thread thread1 = new Thread(() -> {
for (int i = 0; i < vector.size(); i++) {
vector.remove(i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < vector.size(); i++) {
// 例如thread2想获取i=9的元素的时候,thread1将i=9的元素移除了,导致数组越界
vector.get(i);
// log.info("{}", integer);
}
});
thread1.run();
thread2.run();
}
}
}
```
2回答
-
william_michelle
2018-12-23
是start,不是run...
00 -
Jimin
2018-07-09
你好,这个演示的就是同步容器不一定线程安全,这个异常就是证明
022018-07-09
相似问题