java.util.Collections类的synchronizedList()方法用于返回由指定列表支持的同步(线程安全)列表。为了保证串行访问,至关重要的是,对后备列表的所有访问都必须通过返回的列表来完成。
用法:
public static List
synchronizedList(List list)
参数:此方法将列表作为参数,作为同步列表中的“wrapped”。
返回值:此方法返回指定列表的同步视图。
以下示例说明了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
List list = new ArrayList();
// 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 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
List list = new ArrayList();
// 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 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]