引用了
http://www.importnew.com/24822.html
知识点
①hash集合中,不能存在key相同键值对。后面插入的会替换前面的。put(1,100);put(1,200)。get(1)=200。
②hashmap不是线程安全的。
③hashtable是线程安全的。用的是整个数组加锁。
④conCurrentHaskMap是线程安全的。用的是分段加锁,不同的段可以同时插入。所以速度比hashtable略快,同时竞争线程越多,越明显。
原理图
![](https://img.haomeiwen.com/i11678839/c1fc875c04f91073.png)
如果出现key不同,但是不同key的hash相同则会出现链的情况。
代码
hashmap
2000线程竞争,结果本来只应该有1000个,结果为1105个,122ms,可见不是线程安全的。
public class Main{
private static HashMap<Integer, Integer> infos = new HashMap<>();
private static ExecutorService executorService = Executors.newFixedThreadPool(2000);
private static long s = 0;
public static void main(String[] args){
s = System.currentTimeMillis();
for (int i = 0; i < 2000; i++) {
executorService.execute(new MyRunnable());
}
executorService.shutdown();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(infos.size());
}
private static class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++){
infos.put(i, i);
}
System.out.println(System.currentTimeMillis() - s + "ms");
}
}
}
输出:122ms 1105
HashTable
2000线程竞争,数据插入正确为1000,耗时162ms
public class Main{
private static Hashtable<Integer, Integer> infos = new Hashtable<>();
//略
}
输出:162ms 1000
ConCurrentHashMap
2000线程竞争,数据插入正确为1000,耗时131ms,比hashtable快一点。
public class Main{
private static Hashtable<Integer, Integer> infos = new Hashtable<>();
//略
}
输出:131ms 1000
网友评论