并发线程同时添加到 ArrayList - 会发生什么? [英] Concurrent threads adding to ArrayList at same time - what happens?

查看:35
本文介绍了并发线程同时添加到 ArrayList - 会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有多个线程在 ArrayList 上调用 add(obj).

We have multiple threads calling add(obj) on an ArrayList.

我的理论是,当 add 被两个线程并发调用时,被添加的两个对象中只有一个被真正添加到 ArrayList 中.这有道理吗?

My theory is that when add is called concurrently by two threads, that only one of the two objects being added is really added to the ArrayList. Is this plausable?

如果是这样,你如何解决这个问题?使用像 Vector?

If so, how do you get around this? Use a synchronized collection like Vector?

推荐答案

当 ArrayList 上的两个线程同时调用 add 时发生的情况没有保证的行为.但是,根据我的经验,这两个对象都添加得很好.大多数与列表相关的线程安全问题都在添加/删除时处理迭代.尽管如此,我强烈建议不要使用具有多线程和并发访问的 vanilla ArrayList.

There is no guaranteed behavior for what happens when add is called concurrently by two threads on ArrayList. However, it has been my experience that both objects have been added fine. Most of the thread safety issues related to lists deal with iteration while adding/removing. Despite this, I strongly recommend against using vanilla ArrayList with multiple threads and concurrent access.

Vector 曾经是并发列表的标准,但现在标准是使用 集合同步列表.

Vector used to be the standard for concurrent lists, but now the standard is to use the Collections synchronized list.

另外,如果您打算花任何时间在 Java 中处理线程,我强烈推荐 Goetz 等人的 Java Concurrency in Practice.这本书更详细地讨论了这个问题.

Also I highly recommend Java Concurrency in Practice by Goetz et al if you're going to be spending any time working with threads in Java. The book covers this issue in much better detail.

这篇关于并发线程同时添加到 ArrayList - 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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