Java ArrayList.add() 方法线程对于纯并行添加是安全的吗? [英] Java ArrayList.add() method thread safe for purely parallel adding?
问题描述
考虑对接受 ArrayList 引用并将对象添加到该 ArrayList 的函数的 for 循环.我现在想并行执行每个函数调用.
Consider a for-loop over a function that takes an ArrayList reference and adds an object to that ArrayList. I would now like to execute each function call in parallel.
如果我不关心添加对象的顺序并且没有函数读取或操作任何 ArrayList 元素,那么 ArrayList.add() 方法是否线程安全?所以我只想确保在并行调用结束时所有对象都添加到列表中.
Is the ArrayList.add() method thread safe if I don't care about the sequence the objects are added and no function reads or manipulates any ArrayList elements? So I only want to make sure that at the end of the parallel call all objects are added to the list.
推荐答案
不,它不是线程安全的.使用 Collections.synchronizedList()
包装您的列表,或者在访问列表时使用显式同步.
No, it's not thread-safe. Wrap your list using Collections.synchronizedList()
, or use explicit synchronization when accessing the list.
这篇关于Java ArrayList.add() 方法线程对于纯并行添加是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!