ThreadLocal應用------解決線程不安全方法之一,破壞共有資源

ThreadLocal應用

ThreadLocal用於保存某個線程共享變量:對於同一個static ThreadLocal,不同線程只能從中get,set,remove自己的變量,而不會影響其他線程的變量。

1、ThreadLocal.get: 獲取ThreadLocal中當前線程共享變量的值。

2、ThreadLocal.set: 設置ThreadLocal中當前線程共享變量的值。

3、ThreadLocal.remove: 移除ThreadLocal中當前線程共享變量的值。

4、ThreadLocal.initialValue: ThreadLocal沒有被當前線程賦值時或當前線程剛調用remove方法後調用get方法,返回此方法值。

ThreadLocal方法主要破壞了線程不安全三大問題(多線程,公有資源,有寫操作)中的公有資源的條件,來保證線程的安全。

public class ThreadLocalDemo {
    private static ThreadLocal<Object> threadLocal = new ThreadLocal<Object>(){
        @Override
        protected Object initialValue() {
            System.out.println("調用此方法後進行初始化。。");
            return null;
        }
    };
    public static void main(String[] args) {
            new Thread(new addInt(),"int1").start();
            new Thread(new addString(),"string1").start();
            new Thread(new addInt(),"int2").start();
            new Thread(new addString(),"string2").start();
    }

    static class addInt implements  Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 6; i++) {
                if (null == threadLocal.get()){
                    //說明沒有賦初始值
                    threadLocal.set(0);
                    System.out.println("線程:"+Thread.currentThread().getName()+":0");
                }else{
                    int num = (int) threadLocal.get();
                    threadLocal.set(num+1);
                    System.out.println("線程:"+Thread.currentThread().getName()+":"+threadLocal.get());
                    if (i==3){
                        threadLocal.remove();
                    }
                }
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }
    static class addString implements  Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 6; i++) {
                if (null == threadLocal.get()){
                    threadLocal.set("a");
                    System.out.println("線程:"+Thread.currentThread().getName()+":a");
                }else {
                    String a = (String) threadLocal.get();
                    threadLocal.set(a+"a");
                    System.out.println("線程:"+Thread.currentThread().getName()+":"+threadLocal.get());
                }
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }
}
運行結果:
調用此方法後進行初始化。。
線程:int1:0
調用此方法後進行初始化。。
線程:int2:0
調用此方法後進行初始化。。
線程:string2:a
調用此方法後進行初始化。。
線程:string1:a
線程:int2:1
線程:int1:1
線程:string2:aa
線程:string1:aa
線程:int1:2
線程:int2:2
線程:string2:aaa
線程:string1:aaa
線程:int2:3
線程:int1:3
線程:string2:aaaa
線程:string1:aaaa
調用此方法後進行初始化。。
調用此方法後進行初始化。。
線程:int2:0
線程:int1:0
線程:string2:aaaaa
線程:string1:aaaaa
線程:int1:1
線程:int2:1
線程:string2:aaaaaa
線程:string1:aaaaaa

線程共享變量緩存如下:

Thread.ThreadLocalMap<ThreadLocalObject>;

1、Thread: 當前線程,可以通過Thread.currentThread()獲取。

2、ThreadLocal:我們的static ThreadLocal變量。

3、Object: 當前線程共享變量。

我們調用ThreadLocal.get方法時,實際上是從當前線程中獲取ThreadLocalMap<ThreadLocalObject>,然後根據當前ThreadLocal獲取當前線程共享變量Object。

ThreadLocal.set,ThreadLocal.remove實際上是同樣的道理。

這種存儲結構的好處:

1、線程死去的時候,線程共享變量ThreadLocalMap則銷燬。

2、ThreadLocalMap<ThreadLocal,Object>鍵值對數量爲ThreadLocal的數量,一般來說ThreadLocal數量很少,相比在ThreadLocal中用Map<Thread, Object>鍵值對存儲線程共享變量(Thread數量一般來說比ThreadLocal數量多),性能提高很多。

 

關於ThreadLocalMap<ThreadLocalObject>弱引用問題:

當線程沒有結束,但是ThreadLocal已經被回收,則可能導致線程中存在ThreadLocalMap<nullObject>的鍵值對,造成內存泄露。(ThreadLocal被回收,ThreadLocal關聯的線程共享變量還存在)。

雖然ThreadLocal的get,set方法可以清除ThreadLocalMap中key爲null的value,但是get,set方法在內存泄露後並不會必然調用,所以爲了防止此類情況的出現,我們有兩種手段。

1、使用完線程共享變量後,顯示調用ThreadLocalMap.remove方法清除線程共享變量;

2、JDK建議ThreadLocal定義爲private static,這樣ThreadLocal的弱引用問題則不存在了。

參考:https://www.cnblogs.com/coshaho/p/5127135.html

爲什麼ThreadLocal會造成內存泄漏:https://blog.csdn.net/csujiangyu/article/details/52999573

 

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