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


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


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

用法:

public static <T> Collection<T>
  synchronizedCollection(Collection<T> c)

参数:此方法将集合c作为参数,作为同步集合中的“wrapped”。


返回值:此方法返回指定集合的​​同步视图。

以下示例说明了synchronizedCollection()方法

示例1:

// Java program to demonstrate synchronizedCollection() 
// 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> vector = new ArrayList<String>(); 
  
            // populate the vector 
            vector.add("A"); 
            vector.add("B"); 
            vector.add("C"); 
            vector.add("D"); 
            vector.add("E"); 
  
            // printing the Collection 
            System.out.println("Collection : " + vector); 
  
            // getting the syncronised view of Collection 
            Collection<String> c = Collections 
                                       .synchronizedCollection(vector); 
  
            // printing the Collection 
            System.out.println("Synchronized view"
                               + " of collecttion : " + c); 
        } 
  
        catch (IndexOutOfBoundsException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
Collection : [A, B, C, D, E]
Synchronized view of collecttion : [A, B, C, D, E]

示例2:

// Java program to demonstrate synchronizedCollection() 
// method for Integer Value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of List<String> 
            List<Integer> vector = new ArrayList<Integer>(); 
  
            // populate the vector 
            vector.add(20); 
            vector.add(30); 
            vector.add(40); 
            vector.add(50); 
            vector.add(60); 
  
            // printing the Collection 
            System.out.println("Collection : " + vector); 
  
            // getting the syncronised view of Collection 
            Collection<Integer> c = Collections 
                                        .synchronizedCollection(vector); 
  
            // printing the Collection 
            System.out.println("Synchronized view is : " + c); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
Collection : [20, 30, 40, 50, 60]
Synchronized view is : [20, 30, 40, 50, 60]


相关用法


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