问题描述
在Java线程中对数组进行操作是否安全?
Are operations on arrays in Java thread safe?
是否不能通过Java来确保读写操作对数组线程的访问安全?
If not how to make access to an array thread safe in Java for both reads and writes?
推荐答案
在Java中对数组进行操作不是线程安全的.相反,您可以将ArrayList
与Collections.synchronizedList()
Operation on array in java is not thread safe. Instead you may use ArrayList
with Collections.synchronizedList()
假设我们正在尝试填充String的同步ArrayList.然后,您可以将项目添加到列表中,例如-
Suppose we are trying to populate a synchronized ArrayList of String. Then you can add item to the list like -
List<String> list =
Collections.synchronizedList(new ArrayList<String>());
//Adding elements to synchronized ArrayList
list.add("Item1");
list.add("Item2");
list.add("Item3");
然后从这样的synchronized
块访问它们-
Then access them from a synchronized
block like this -
synchronized(list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
或者您可以使用ArrayList的线程安全变体- CopyOnWriteArrayList .可以在此处一个>.
Or you may use a thread safe variant of ArrayList - CopyOnWriteArrayList. A good example can be found here.
希望这会有所帮助.
这篇关于如何在Java中安全地访问数组线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!