且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中安全地访问数组线程?

更新时间:2023-02-16 08:07:57

在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.

希望这会有所帮助.