當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。