Java ArrayList.add()方法线程可安全用于纯并行添加吗?

编程入门 行业动态 更新时间:2024-10-17 21:28:35
本文介绍了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()方法线程可安全用于纯并行添加吗?

本文发布于:2023-11-06 23:49:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:法线   ArrayList   Java   程可   add

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!