📜  Java中的集合 synchronizedList() 方法及示例

📅  最后修改于: 2022-05-13 01:54:46.324000             🧑  作者: Mango

Java中的集合 synchronizedList() 方法及示例

Java.util.Collections类的synchronizedList()方法用于返回由指定列表支持的同步(线程安全)列表。为了保证串行访问,对后备列表的所有访问都通过返回的列表完成是至关重要的。

句法:

public static  List
  synchronizedList(List 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
            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]