💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 如何在 Java 中同步`HashMap` > 原文: [https://beginnersbook.com/2013/12/how-to-synchronize-hashmap-in-java-with-example/](https://beginnersbook.com/2013/12/how-to-synchronize-hashmap-in-java-with-example/) [`HashMap`是一个非同步的集合类](https://beginnersbook.com/2013/12/hashmap-in-java-with-example/)。如果我们需要对它执行线程安全操作,那么我们必须明确地同步它。在本教程中,我们将了解如何同步`HashMap`。 #### 示例: 在这个例子中,我们有一个`HashMap<Integer, String>`它具有整数键和字符串类型值。为了同步它,我们使用[`Collections.synchronizedMap(hashmap)`](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map))。它返回由指定的`HashMap`备份的线程安全映射。 **以下示例中需要注意的重要事项:** 迭代器应该在同步块中使用,即使我们已经明确地同步了`HashMap`(正如我们在下面的代码中所做的那样)。 **语法:** ```java Map map = Collections.synchronizedMap(new HashMap()); ... //This doesn't need to be in synchronized block Set set = map.keySet(); // Synchronizing on map, not on set synchronized (map) { // Iterator must be in synchronized block Iterator iterator = set.iterator(); while (iterator.hasNext()){ ... } } ``` **完整代码:** ```java package beginnersbook.com; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Iterator; public class HashMapSyncExample { public static void main(String args[]) { HashMap<Integer, String> hmap= new HashMap<Integer, String>(); hmap.put(2, "Anil"); hmap.put(44, "Ajit"); hmap.put(1, "Brad"); hmap.put(4, "Sachin"); hmap.put(88, "XYZ"); Map map= Collections.synchronizedMap(hmap); Set set = map.entrySet(); synchronized(map){ Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } } ``` 输出: ```java 1: Brad 2: Anil 4: Sachin 88: XYZ 44: Ajit ```