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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。