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

查看:92
本文介绍了如何在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的线程安全变体-此处.

Or you may use a thread safe variant of ArrayList - CopyOnWriteArrayList. A good example can be found here.

希望这会有所帮助.

这篇关于如何在Java中安全地访问数组线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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