HashMap簡單的實現ThreadLocal

/**  * 用HashMap簡單的實現ThreadLocal  */ import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.Test; public class MyThreadLocal {  /**   * 用一個弱引用保存value,便於線程結束後垃圾回收器的回收   */    private static Map<Thread,WeakReference<Integer>> map=new HashMap<Thread,WeakReference<Integer>>();    public static Integer getNum(){     //第一次先得WeakReference     WeakReference<Integer> refer=map.get(Thread.currentThread());     if(refer==null){     //若爲空,獲得一個隨機數,用這個隨機數建立一個WeakReference對象,做爲value存入map      Random random=new Random();      int number = random.nextInt(100);      refer=new WeakReference<Integer>(number);      map.put(Thread.currentThread(),refer );     }     //返回weakReference裏保存的number     return refer.get();    }    /**     *如下是測試代碼     */    public static void main(String[] args) {     Integer num1 = MyThreadLocal.getNum();     Integer num2 = MyThreadLocal.getNum();     System.out.println(num1+":::"+num2);     new Thread(){      @Override   public void run() {    Integer num3 = MyThreadLocal.getNum();    Integer num4 = MyThreadLocal.getNum();    System.out.println(num3+":::"+num4);   }     }.start();  } } 
相關文章
相關標籤/搜索