当多个线程向其中添加元素时,为什么arraylist的大小不正确? [英] Why is arraylist's size not right when multiple threads add elements into it?
问题描述
当多个线程向其中添加元素时,为什么Arraylist的大小不正确?
Why is Arraylist's size not right when multiple threads add elements into it?
threadCount = 100;
List<Object> list = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new MyThread(list, countDownLatch));
thread.start();
}
class MyThread implements Runnable {
// ......
@Override
public void run() {
for (int i = 0; i < 100; i++) {
list.add(new Object());
}
}
}
完成此程序后,列表的大小应为10000.实际上,大小可以为9950、9965或其他一些数字.为什么?
When this program is done, the size of the list should be 10000. Actually, the size may be 9950, 9965 or some other numbers. Why?
我知道为什么该程序可能会引发IndexOutofBoundsException
以及为什么其中包含一些null,但是我只是不明白为什么大小错误.
I know that why this program may raise IndexOutofBoundsException
and why there are some nulls in it, but I just do not understand why the size is wrong.
推荐答案
我只是不明白为什么尺寸不正确?
I just do not understand why the size is wrong?
由于ArrayList不是线程安全的,因此两个线程可以在同一索引处添加.因此,一个线程将覆盖.
As ArrayList is not thread-safe so two threads may add at same index. So one thread overwrites.
这篇关于当多个线程向其中添加元素时,为什么arraylist的大小不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!