首页>itarticle>how to synchronize arraylist in java with example
how to synchronize arraylist in java with example
admin11月 12, 20200
There are two ways to synchronize explicitly:
Using Collections.synchronizedList() method
Using thread-safe variant of ArrayList: CopyOnWriteArrayList
Example 1: Collections.synchronizedList() method for Synchronizing ArrayList
In this example we are using Collections.synchronizedList() method. The important point to note here is that iterator should be in synchronized block in this type of synchronization as shown in the below example.
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()); } }
近期评论