当多个线程向其中添加元素时,为什么 arraylist 的大小不正确? [英] Why is arraylist's size not right when multiple threads add elements into it?

查看:40
本文介绍了当多个线程向其中添加元素时,为什么 arraylist 的大小不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多线程添加元素时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 以及为什么其中有一些空值,但我只是不明白为什么大小是错误的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆