如何在 Java 中安全地访问数组线程? [英] How to access an array thread safely in Java?

查看:38
本文介绍了如何在 Java 中安全地访问数组线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 中对数组的操作不是线程安全的.相反,您可以使用 ArrayListCollections.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 中安全地访问数组线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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