📜  Java中的集合 synchronizedMap() 方法及示例

📅  最后修改于: 2022-05-13 01:54:52.553000             🧑  作者: Mango

Java中的集合 synchronizedMap() 方法及示例

Java.util.Collections类的synchronizedMap()方法用于返回由指定映射支持的同步(线程安全)映射。为了保证串行访问,对支持映射的所有访问都是通过返回的映射完成的,这一点至关重要。

句法:

参数:此方法将地图作为参数“包装”在同步地图中。

返回值:此方法返回指定地图的同步视图

下面是说明synchronizedMap()方法的示例。

示例 1:

// Java program to demonstrate
// synchronizedMap() method
// for  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of Map
            Map
                map = new HashMap();
  
            // 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
                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  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of Map
            Map
                map = new HashMap();
  
            // 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
                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}