java ThreadLocal 使用

ThreadLocal
    線程內 threadLocal.set(), 只是當前線程能 threadLocal.get() 到
    只能設置一個對象,可set map對象。
    容易造成內存泄漏,每次使用完ThreadLocal,都調用它的remove()方法,清除數據

/**
 * ThreadLocal的set的變量只是當前線程可看
 * ThreadLocal set的變量只有一個,經常set Map
 */
public class ThreadLocalTest {

    static ThreadLocal threadLocal = new ThreadLocal();

    public static void main(String[] args) {

        new Thread(()->{
            System.out.println("線程1");
            Map<String,String> dataMap = new HashMap<>();
            threadLocal.set(dataMap);//往當前線程裏面設置個對象 map,其它線程得不到這個數據
            System.out.println("線程1 往線程變量中 加入數據 ");
            dataMap.put("name","thread1");
            Map<String,String> getMap = (Map<String, String>) threadLocal.get();//從當前線程把對象拿出
            System.out.println("線程1 get:"+getMap.get("name"));
        }).start();

        new Thread(()->{
            try {
                System.out.println("線程2 等待1秒 讓線程1 先執行完");
                Thread.sleep(1000);
                System.out.println("線程2 是否能拿取線程1 線程變量是否爲空 結果:"+ (threadLocal.get() == null));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

執行結果:

線程1
線程1 往線程變量中 加入數據 
線程1 get:thread1
線程2 等待1秒 讓線程1 先執行完
線程2 是否能拿取線程1 線程變量是否爲空 結果:true

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章