本地線程管理、仿ThreadLocal

在實際項目中,通常有這樣的要求,對於同一個線程內多次請求獲取對象,對象要求必須爲同一個(如數據多表庫多表進行事務處理,請求的連接對象必須爲同一個),這就要用到線程管理技術。

線程管理,涉及到一個核心的類,java.lang.ThreadLocal,通過這個類來僅實現相應的功能。
這裏寫圖片描述

代碼演示:

public class ThreadLocalDemo {

   private static ThreadLocal<Object> t1 = new ThreadLocal<Object>();

   public static Object getValue(){
       Object o = t1.get();//不用給key,因爲t1內部會自動獲取當前線程的thread對象,並以上作爲key到它的池中去

取obj
       if(o==null){
           System.out.println("空的....");
           Random r = new Random();
           o = r.nextInt(1000);
           t1.set(o);
       }
       return o;
   }

   @Test
   public void test(){
       Object obj = getValue();
       Object obj2 = getValue();
       System.out.println(obj+","+obj2);
       System.out.println(obj==obj2);   //true

      A a = new A();
      Object obj3 = a.aa();
      System.out.println(obj==obj3);    //true

      B b = new B();
      Object obj4 = b.bb();
      System.out.println(obj3==obj4);   //true

      System.out.println("=================");

      new Thread(){
        @Override
        public void run() {
             A a = new A();
             Object obj5 = a.aa();
             System.out.println("obj5:"+obj5);
             B b = new B();
              Object obj6 = b.bb();
              System.out.println("obj6:"+obj6);
              System.out.println(obj5==obj6);  //true
        }
      }.start();

   }

}

class A{
    public Object aa(){
        Object obj3 = ThreadLocalDemo.getValue();
        System.out.println(obj3);
        return obj3;
    }
}
class B{
    public Object bb(){
        Object obj4 = ThreadLocalDemo.getValue();
        System.out.println(obj4);
        return obj4;
    }
}

仿ThreadLocal功能:

public class MyThreadLocal {
    private Map<Thread,Object>map = new HashMap<Thread,Object>();

    public Object get(){
        Thread currentThread = Thread.currentThread();
        Object obj = map.get(currentThread);
        return obj;
    }

    public void set(Object obj){
        Thread currentThread = Thread.currentThread();
        map.put(currentThread,obj);
    }
}
發佈了76 篇原創文章 · 獲贊 53 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章