Java ArrayList.add()方法线程可安全用于纯并行添加吗? [英] Java ArrayList.add() method thread safe for purely parallel adding?

查看:374
本文介绍了Java ArrayList.add()方法线程可安全用于纯并行添加吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个接受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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆