java HashMap问题
生活随笔
收集整理的這篇文章主要介紹了
java HashMap问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java 的HashMap是Map接口的一個實現,采用的是key-value鍵值存儲,其中key是不能重復的,對于重復的key,將覆蓋其value。同時HashMap的線程不安全的。
今天寫了這樣一個多線程代碼,發現一個問題不理解,希望通過博客園的高手給予解答。
package com.mesnac.qc.A1;import java.util.HashMap; import java.util.Hashtable;public class Foo {private int x = 100;private HashMap hMap = new HashMap();private Hashtable hTab = new Hashtable();public int getX(){return x;}public HashMap getHMap(){return hMap;}public Hashtable getHTab(){return hTab;}public Hashtable htb(Object key,Object value){hTab.put(key, value);return hTab;}public HashMap hfx(Object key,Object value){hMap.put(key, value);return hMap;}public int fix(int y){synchronized(this){x = x - y;}return x;} } package com.mesnac.qc.A1;import java.util.HashMap; import java.util.Hashtable;public class MyRunable implements Runnable{private Foo a1 = new Foo();public void run(){for(int i = 0;i < 3; i++){a1.fix(20);a1.hfx(Integer.valueOf(i), Integer.valueOf(i));a1.htb(Integer.valueOf(i), Integer.valueOf(i));try {Thread.sleep(1);} catch (Exception e) {// TODO: handle exception }System.out.println(Thread.currentThread().getName()+"當前Foo值"+a1.getX());System.out.println(Thread.currentThread().getName()+"當前HMAP值"+a1.getHMap());System.out.println(Thread.currentThread().getName()+"當前HTable值"+a1.getHTab());}}public static void main(String args[]){MyRunable aMyRunable = new MyRunable();Thread a = new Thread(aMyRunable,"Thread-A");Thread bThread = new Thread(aMyRunable,"Thread-B");a.start();bThread.start();HashMap t1 = new HashMap();t1.put(Integer.valueOf(0), Integer.valueOf(0));t1.put(Integer.valueOf(0), Integer.valueOf(0));t1.put(Integer.valueOf(0), Integer.valueOf(0));t1.put(Integer.valueOf(0), Integer.valueOf(0));Hashtable t2 = new Hashtable();t2.put(Integer.valueOf(0), Integer.valueOf(0));t2.put(Integer.valueOf(0), Integer.valueOf(0));t2.put(Integer.valueOf(0), Integer.valueOf(0));t2.put(Integer.valueOf(0), Integer.valueOf(0));t2.put(Integer.valueOf(0), Integer.valueOf(1));System.out.println(t1);System.out.println(t2);}}主要是兩個線程去操作HashMap。我知道線程不安全,但是多次運行這個程序。會發現HashMap中存在 {2=2,1=1,0=0,0=0}的情況,查閱JDK,發現HashMap的存儲是根據key獲得一個hash值,然后執行key1==null?key2==null:key1.equal(key2)的算法,不理解為什么會產生重復的值。難道是因為第一個0,0存入的時候,執行到hash算法之后,但是沒保存,第二個線程也執行到判斷,這樣兩個都保存進去了么?
?
希望博客園大牛給予解答。。。
轉載于:https://www.cnblogs.com/snail-tomorrow/archive/2012/07/04/2575731.html
總結
以上是生活随笔為你收集整理的java HashMap问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EM算法【图像迭代】
- 下一篇: 神经网络不学习的原因