并发线程增加ArrayList的在同一时间 - 会发生什么? [英] Concurrent threads adding to ArrayList at same time - what happens?

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

问题描述

我们有多个线程调用添加(OBJ)上的的ArrayList

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

我的理论是,当添加是同时被两个线程调用,只有添加真的添加到 ArrayList中的两个对象之一。这是plausable?

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的两个线程同时调用发生了什么没有保证行为。然而,它一直是我的经验,这两个对象已添加的罚款。大部分涉及到列表中的线程安全问题处理迭代,同时添加/删除。尽管这样,我强烈建议不要使用香草的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.

矢量用于为并发列出的标准,但现在的标准是使用<一href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList(java.util.List)\">Collections同步列表。

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

此外,我强烈推荐的Java并发由Goetz等人练习,如果你要花费任何时间在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天全站免登陆