当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collections synchronizedList()用法及代码示例


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

用法:

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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections synchronizedList() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。