Java Collections synchronizedList()方法及实例
java.util.Collections 类的 synchronizedList() 方法是用来返回一个由指定列表支持的同步(线程安全)列表。为了保证串行访问,对支持列表的所有访问都是通过返回的列表完成的,这一点至关重要。
语法
public static <T> List<T>
synchronizedList(List<T> list)
参数: 该方法以列表为参数,将其 “包装 “成一个同步列表。
返回值: 该方法返回一个指定列表的同步视图。
下面是说明 synchronizedList() 方法的例子
例子 1 :
// Java program to demonstrate
// synchronizedList() method for String Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List<String>
List<String> list = new ArrayList<String>();
// populate the list
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// printing the Collection
System.out.println("List : " + list);
// create a synchronized list
List<String> synlist = Collections
.synchronizedList(list);
// printing the Collection
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
List : [A, B, C, D, E]
Synchronized list is : [A, B, C, D, E]
例2 :
// Java program to demonstrate
// synchronizedList() method for Integer Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of List<Integer>
List<Integer> list = new ArrayList<Integer>();
// populate the list
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
// printing the Collection
System.out.println("List : " + list);
// create a synchronized list
List<Integer> synlist = Collections
.synchronizedList(list);
// printing the Collection
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
List : [20, 30, 40, 50, 60]
Synchronized list is : [20, 30, 40, 50, 60]