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


Java Collections synchronizedMap()用法及代碼示例


java.util.Collections類的synchronizedMap()方法用於返回由指定映射支持的同步(線程安全)映射。為了保證串行訪問,至關重要的是,對後備映射的所有訪問都必須通過返回的映射來完成。

用法:

public static <K, V> MapK, V>
  synchronizedMap(MapK, V> m)

參數:該方法在同步映射中將映射作為參數“wrapped”。


返回值:此方法返回指定Map的同步視圖。

以下示例說明了synchronizedMap()方法

示例1:

// Java program to demonstrate 
// synchronizedMap() method 
// for <String, String> Value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of Map<String, String> 
            Map<String, String> 
                map = new HashMap<String, String>(); 
  
            // populate the map 
            map.put("Value1", "20"); 
            map.put("Value2", "30"); 
            map.put("Value3", "40"); 
  
            // printing the Collection 
            System.out.println("Map : " + map); 
  
            // create a synchronized map 
            Map<String, String> 
                synmap = Collections.synchronizedMap(map); 
  
            // printing the Collection 
            System.out.println("Synchronized map is : "
                               + synmap); 
        } 
  
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Map : {Value3=40, Value1=20, Value2=30}
Synchronized map is : {Value3=40, Value1=20, Value2=30}

示例2:

// Java program to demonstrate 
// synchronizedMap() method 
// for <String, Boolean> Value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of Map<String, Boolean> 
            Map<String, Boolean> 
                map = new HashMap<String, Boolean>(); 
  
            // populate the map 
            map.put("Bramha", true); 
            map.put("Vishnu", true); 
            map.put("Mahesh", true); 
  
            // printing the Collection 
            System.out.println("Map : " + map); 
  
            // create a synchronized map 
            Map<String, Boolean> 
                synmap = Collections.synchronizedMap(map); 
  
            // printing the Collection 
            System.out.println("Synchronized map is : "
                               + synmap); 
        } 
        catch (IllegalArgumentException e) { 
  
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Map : {Bramha=true, Vishnu=true, Mahesh=true}
Synchronized map is : {Bramha=true, Vishnu=true, Mahesh=true}


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections synchronizedMap() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。