考虑一个接受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()方法线程可安全用于纯并行添加吗?
发布评论