多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 如何在 java 中同步`ArrayList` > 原文: [https://beginnersbook.com/2013/12/how-to-synchronize-arraylist-in-java-with-example/](https://beginnersbook.com/2013/12/how-to-synchronize-arraylist-in-java-with-example/) 当我们在[`Vector` vs `ArrayList`](https://beginnersbook.com/2013/12/difference-between-arraylist-and-vector-in-java/) 上共享教程时,我们已经讨论了一些关于同步的问题。我们知道`ArrayList`是非同步的,不应在没有显式同步的多线程环境中使用。这篇文章将讨论如何在 Java 中同步`ArrayList`。 **显式同步有两种方法:** 1. 使用`Collections.synchronizedList()`方法 2. 使用`ArrayList`的线程安全变体:`CopyOnWriteArrayList` ### 示例 1:用于同步`ArrayList`的`Collections.synchronizedList()`方法 在这个例子中,我们使用 [`Collections.synchronizedList()`](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List))方法。这里要注意的重点是迭代器应该在这种类型的同步中处于同步块中,如下例所示。 ```java package beginnersbook.com; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Collections; public class Details { public static void main(String a[]){ List<String> syncal = Collections.synchronizedList(new ArrayList<String>()); //Adding elements to synchronized ArrayList syncal.add("Pen"); syncal.add("NoteBook"); syncal.add("Ink"); System.out.println("Iterating synchronized ArrayList:"); synchronized(syncal) { Iterator<String> iterator = syncal.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } } ``` 输出: ```java Iterating synchronized ArrayList: Pen NoteBook Ink ``` ### 方法 2:使用`CopyOnWriteArrayList` [CopyOnWriteArrayList](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) 是`ArrayList`的线程安全变体。 ```java package beginnersbook.com; import java.util.concurrent.CopyOnWriteArrayList; import java.util.Iterator; public class Details { public static void main(String a[]){ CopyOnWriteArrayList<String> al = new CopyOnWriteArrayList<String>(); //Adding elements to synchronized ArrayList al.add("Pen"); al.add("NoteBook"); al.add("Ink"); System.out.println("Displaying synchronized ArrayList Elements:"); //Synchronized block is not required in this method Iterator<String> iterator = al.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } ``` 输出: ```java Displaying synchronized ArrayList Elements: Pen NoteBook Ink ```