HashMap是一个非同步的集合类。如果我们需要对它执行线程安全操作,那么我们必须明确地同步它。在本教程中,我们将了解如何同步HashMap。
示例:
在这个例子中,我们有一个HashMap<Integer, String>它具有整数键和字符串类型值。为了同步它,我们使用Collections.synchronizedMap(hashmap)。它返回由指定的HashMap备份的线程安全映射。
以下示例中需要注意的重要事项:
迭代器应该在同步块中使用,即使我们已经明确地同步了HashMap(正如我们在下面的代码中所做的那样)。
语法:
Map map = Collections.synchronizedMap(new HashMap());...//This doesn't need to be in synchronized blockSet set = map.keySet();// Synchronizing on map, not on setsynchronized (map) { // Iterator must be in synchronized block Iterator iterator = set.iterator(); while (iterator.hasNext()){ ... }}完整代码:
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()); } } }}
输出:
1: Brad2: Anil4: Sachin88: XYZ44: Ajit
