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

查看:1229
本文介绍了并发线程同时添加到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?

如果是,您如何解决这个问题?使用向量?

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 used to be the standard for concurrent lists, but now the standard is to use the Collections synchronized list.

此外,我强烈推荐Goetz等人的Java Concurrency in Practice,如果你要花费任何时间使用Java中的线程。本书更详细地介绍了这个问题。

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天全站免登陆