📜  从Java HashMap 获取同步映射

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

从Java HashMap 获取同步映射

HashMap 是一个非同步集合类。如果我们想对它执行线程安全的操作,那么我们必须显式地同步它。为了显式地同步它, Java.util.Collections类的synchronizedMap()方法用于返回由指定映射支持的同步(线程安全)映射。

// Get synchronized map using Collections.synchronizedMap()

Map synchrMap = Collections.synchronizedMap(hmap);

为了迭代同步映射,我们使用了一个同步块

// Synchronized block
synchronized (synchrMap) {

      // Iterate synchronized map
      for (Map.Entry entry : synchrMap.entrySet()) {

        // Print key : value
        System.out.println(entry.getKey() + " : " + entry.getValue());
        
      }
}

执行:

Java
// Java Program to demonstrate how 
// to get synchronized map from HashMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // New HashMap
        HashMap hmap = new HashMap<>();
  
        // Add element to map
        hmap.put(1, "Akshay");
        hmap.put(2, "Bina");
        hmap.put(3, "Chintu");
  
        // Get synchronized map using
        // Collections.synchronizedMap()
        Map synchrMap = Collections.synchronizedMap(hmap);
  
        System.out.println("Synchronized Map : ");
  
        // Synchronized block
        synchronized (synchrMap)
        {
  
            // Iterate synchronized map
            for (Map.Entry entry :
                 synchrMap.entrySet()) {
  
                // Print key : value
                System.out.println(entry.getKey() + " : "
                                   + entry.getValue());
            }
        }
    }
}


输出
Synchronized Map : 
1 : Akshay
2 : Bina
3 : Chintu