23,404
社区成员
发帖
与我相关
我的任务
分享
package com.lzw.test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MapTest
{
/*
Map小结:
预置条件:多个线程操作Map
1.使用new HashMap会抛出java.util.ConcurrentModificationException 能够使用null做键与值
2.使用Collections.synchronizedMap(new HashMap<String, String>()),在迭代的时候需要同步.如下:
synchronized (map){
for (Entry<String, String> entry : map.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
3.JDK1.5新特性, ConcurrentHashMap类遵守与 Hashtable 相同的功能规范,线程同步,不允许使用null作为键值等.
*/
/*
预置条件:数据为1000000
HashMap使用时间:1844
Collections.synchronizedMap使用时间:1813
ConcurrentHashMap使用时间:1437
Hashtable使用时间:749
*/
public static void main(String[] args)
{
// Map<Integer, Integer> map1 =Collections.synchronizedMap(new HashMap<Integer, Integer>());
// Map<Integer, Integer> map2 =new HashMap<Integer, Integer>();
// Map<Integer, Integer> map3 =new ConcurrentHashMap<Integer, Integer>();
// Map<Integer, Integer> map4 =new Hashtable<Integer, Integer>();
// //注意:是用new的时候能不获得实例句柄, 就最好不去获得. 因为数据量太大会造成堆栈溢出..
// MapTest.countTime(map1, "map1");
// MapTest.countTime(map2, "map2");
// MapTest.countTime(map3, "map3");
// MapTest.countTime(map4, "map4");
MapTest.countTime(Collections.synchronizedMap(new HashMap<Integer, Integer>()), "Collections.synchronizedMap");
MapTest.countTime(new HashMap<Integer, Integer>(), "HashMap");
MapTest.countTime(new ConcurrentHashMap<Integer, Integer>(), "ConcurrentHashMap");
MapTest.countTime(new Hashtable<Integer, Integer>(), "Hashtable");
}
public static void countTime(Map<Integer, Integer> map, String mapName)
{
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
{
map.put(i, i);
}
System.out.println(mapName + "使用时间:" + (System.currentTimeMillis() - start));
map = null;
System.gc();
}
}