插入元素到不同线程的特定索引,对于ArrayList来说是安全的吗?

huangapple 未分类评论46阅读模式
英文:

Is inserting elements into specific indices from different threads safe using an ArrayList?

问题

我不认为多个线程在ArrayList的特定索引处添加项目会出现问题。假设列表不会调整大小,这里没有竞争条件。这个假设是错误的吗?

英文:

I don't see a problem in multiple threads adding items to specific indices in an ArrayList. Assume that the list will not be resized. There are no race conditions here. Is this assumption wrong?

答案1

得分: 0

你需要使ArrayList线程安全。

Collections.synchronizedList(new ArrayList<YourClassNameHere>())

这可以创建一个线程安全的ArrayList对象。

注意:线程安全意味着相同的数据可以从不同的线程/进程中访问。

英文:

you need to make the ArrayList Thread Safe.

Collections.synchronizedList(new ArrayList&lt;YourClassNameHere&gt;())

this can create a thread safe ArrayList Object.

Note: Thread Safe means that the same data can be accessed from different Thread/Processes.

答案2

得分: 0

假设每个线程只被分配一个索引,那么每个线程不一定会看到数组中其他索引的更新,因为在另一个线程的写操作和当前线程对索引的读操作之间没有先行发生关系。有一些类型可以为这些操作提供安全性。

英文:

Assuming each thread is only allotted one index then each thread would not necessarily see updates to any of the other indices in the array because there is no happens-before relationship between another thread's write and the current threads read of the indices. There are some types that do offer safety for these kinds of operations.

huangapple
  • 本文由 发表于 2020年4月7日 05:30:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/61069287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定