一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - 深入解析Java中ThreadLocal線程類的作用和用法

深入解析Java中ThreadLocal線程類的作用和用法

2020-04-29 12:07熔巖 JAVA教程

ThreadLocal為解決多線程程序的并發問題提供了一種新的思路,ThreadLocal并不是一個Thread,而是Thread的局部變量,本文就來深入解析Java中ThreadLocal線程類的作用和用法.

ThreadLocal與線程成員變量還有區別,ThreadLocal該類提供了線程局部變量。這個局部變量與一般的成員變量不一樣,ThreadLocal的變量在被多個線程使用時候,每個線程只能拿到該變量的一個副本,這是Java API中的描述,通過閱讀API源碼,發現并非副本,副本什么概念?克隆品? 或者是別的樣子,太模糊。
 
準確的說,應該是ThreadLocal類型的變量內部的注冊表(Map<Thread,T>)發生了變化,但ThreadLocal類型的變量本身的確是一個,這才是本質!
 
下面就做個例子:
 
一、標準例子
 
定義了MyThreadLocal類,創建它的一個對象tlt,分別給四個線程使用,結果四個線程tlt變量并沒有出現共用現象,二是各用各的,這說明,四個線程使用的是tlt的副本(克隆品)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 使用了ThreadLocal的類
*/
public class MyThreadLocal {
    //定義了一個ThreadLocal變量,用來保存int或Integer數據
    private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
 
    public Integer getNextNum() {
        //將tl的值獲取后加1,并更新設置t1的值
        tl.set(tl.get() + 1);
        return tl.get();
    }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 測試線程
*/
public class TestThread extends Thread {
    private MyThreadLocal tlt = new MyThreadLocal();
 
    public TestThread(MyThreadLocal tlt) {
        this.tlt = tlt;
    }
 
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + tlt.getNextNum());
        }
    }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* ThreadLocal測試
*/
public class Test {
    public static void main(String[] args) {
        MyThreadLocal tlt = new MyThreadLocal();
        Thread t1 = new TestThread(tlt);
        Thread t2 = new TestThread(tlt);
        Thread t3 = new TestThread(tlt);
        Thread t4 = new TestThread(tlt);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
 
    }
}

 
可以看出,三個線程各自獨立編號,互不影響:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-2 1
Thread-3 1
Thread-2 2
Thread-3 2
Thread-2 3
Thread-3 3
 
 
Process finished with exit code 0

 
tlt對象是一個,廢話tl對象也是一個,因為組合關系是一對一的。但是tl對象內部的Map隨著線程的增多,會創建很多Integer對象。只是Integer和int已經通用了。所以感覺不到Integer的對象屬性。
 
二、不用ThreadLocal
 
假如不用ThreadLocal,只需要將MyThreadLocal類重新定義為:

?
1
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 使用了ThreadLocal的類
*/
public class MyThreadLocal {
    private Integer t1 = 0;
    public Integer getNextNum(){
        return t1=t1+1;
    }
 
 
 
//    定義了一個ThreadLocal變量,用來保存int或Integer數據
//    private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };
//
//    public Integer getNextNum() {
//        //將tl的值獲取后加1,并更新設置t1的值
//        tl.set(tl.get() + 1);
//        return tl.get();
//    }
}

 
然后運行測試:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Thread-2 1
Thread-2 2
Thread-1 4
Thread-1 6
Thread-3 3
Thread-3 9
Thread-3 10
Thread-1 8
Thread-0 7
Thread-0 11
Thread-0 12
Thread-2 5
 
Process finished with exit code 0

 
從這里可以看出,四個線程共享了tlt變量,結果每個線程都直接修改tlt的屬性。
 
三、自己實現個ThreadLocal
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.lavasoft.test2;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
/**
* 使用了ThreadLocal的類
*/
public class MyThreadLocal {
 
    //定義了一個ThreadLocal變量,用來保存int或Integer數據
    private com.lavasoft.test2.ThreadLocal<Integer> tl = new com.lavasoft.test2.ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
 
    public Integer getNextNum() {
        //將tl的值獲取后加1,并更新設置t1的值
        tl.set(tl.get() + 1);
        return tl.get();
    }
}
 
class ThreadLocal<T> {
    private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>());
 
    public ThreadLocal() {
    }
 
    protected T initialValue() {
        return null;
    }
 
    public T get() {
        Thread t = Thread.currentThread();
        T obj = map.get(t);
        if (obj == null && !map.containsKey(t)) {
            obj = initialValue();
            map.put(t, obj);
        }
        return obj;
    }
 
    public void set(T value) {
        map.put(Thread.currentThread(), value);
    }
 
    public void remove() {
        map.remove(Thread.currentThread());
    }
}

 
運行測試:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Thread-0 1
Thread-0 2
Thread-0 3
Thread-2 1
Thread-2 2
Thread-3 1
Thread-2 3
Thread-3 2
Thread-1 1
Thread-3 3
Thread-1 2
Thread-1 3
 
Process finished with exit code 0

 
很意外,這個山寨版的ThreadLocal也同樣運行很好,實現了JavaAPI中ThreadLocal的功能。
 
四、透過現象看本質

 
其實從程序角度看,tlt變量的確是一個,毫無疑問的。但是為什么打印出來的數字就互不影響呢?
是因為使用了Integer嗎?-----不是。
原因是:protected T initialValue()和get(),因為每個線程在調用get()時候,發現Map中不存在就創建。調用它的時候,就創建了一個新變量,類型為T。每次都新建,當然各用個的互不影響了。
為了看清本質,將Integer換掉,重寫部分類:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.lavasoft.test2;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
/**
* 使用了ThreadLocal的類
*/
public class MyThreadLocal {
 
    //定義了一個ThreadLocal變量,用來保存int或Integer數據
    //    private ThreadLocal<Bean> tl = new ThreadLocal<Bean>() {
    private com.lavasoft.test2.ThreadLocal<Bean> tl = new com.lavasoft.test2.ThreadLocal<Bean>() {
        @Override
        protected Bean initialValue() {
            return new Bean();
        }
    };
 
    @Override
    public String toString() {
        return "MyThreadLocal{" +
                "tl=" + tl +
                '}';
    }
 
    public Bean getBean() {
        return tl.get();
    }
 
}
 
class ThreadLocal<T> {
    private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>());
 
    public ThreadLocal() {
    }
 
    protected T initialValue() {
        return null;
    }
 
    public T get() {
        Thread t = Thread.currentThread();
        T obj = map.get(t);
        if (obj == null && !map.containsKey(t)) {
            obj = initialValue();
            map.put(t, obj);
        }
        return obj;
    }
 
    public void set(T value) {
        map.put(Thread.currentThread(), value);
    }
 
    public void remove() {
        map.remove(Thread.currentThread());
    }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.lavasoft.test2;
 
/**
* 測試Bean
*/
public class Bean {
    private String id = "0";
    private String name = "none";
 
    public Bean() {
    }
 
    public Bean(String id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String showinfo() {
        return "Bean{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.lavasoft.test2;
 
/**
* 測試線程
*/
public class TestThread extends Thread {
    private MyThreadLocal tlt = new MyThreadLocal();
 
    public TestThread(MyThreadLocal tlt) {
        this.tlt = tlt;
    }
 
    @Override
    public void run() {
        System.out.println(">>>>>:" + tlt);
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" +tlt.getBean()+"\t"+tlt.getBean().showinfo());
        }
    }
}

 
然后運行測試:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
 
 
Process finished with exit code 0

 
從打印結果很清楚的看到,MyThreadLocal的tlt對象的確是一個,tlt對象里的ThreadLocal的tl對象也是一個,但是,將t1t給每個線程用的時候,線程會重新創建Bean對象加入到ThreadLocal的Map中去使用。


關于ThreadLocal的幾個誤區:
一、ThreadLocal是java線程的一個實現

ThreadLocal的確是和java線程有關,不過它并不是java線程的一個實現,它只是用來維護本地變量。針對每個線程,提供自己的變量版本,主要是為了避免線程沖突,每個線程維護自己的版本。彼此獨立,修改不會影響到對方。

二、ThreadLocal是相對于每個session的

ThreadLocal顧名思義,是針對線程。在java web編程上,每個用戶從開始到會話結束,都有自己的一個session標識。但是ThreadLocal并不是在會話層上。其實,Threadlocal是獨立于用戶session的。它是一種服務器端行為,當服務器每生成一個新的線程時,就會維護自己的ThreadLocal。

對于這個誤解,個人認為應該是開發人員在本地基于一些應用服務器測試的結果。眾所周知,一般的應用服務器都會維護一套線程池,也就是說,對于每次訪問,并不一定就新生成一個線程。而是自己有一個線程緩存池。對于訪問,先從緩存池里面找到已有的線程,如果已經用光,才去新生成新的線程。

所以,由于開發人員自己在測試時,一般只有他自己在測,這樣服務器的負擔很小,這樣導致每次訪問可能是共用同樣一個線程,導致會有這樣的誤解:每個session有一個ThreadLocal

三、ThreadLocal是相對于每個線程的,用戶每次訪問會有新的ThreadLocal

理論上來說,ThreadLocal是的確是相對于每個線程,每個線程會有自己的ThreadLocal。但是上面已經講到,一般的應用服務器都會維護一套線程池。因此,不同用戶訪問,可能會接受到同樣的線程。因此,在做基于TheadLocal時,需要謹慎,避免出現ThreadLocal變量的緩存,導致其他線程訪問到本線程變量

四、對每個用戶訪問,ThreadLocal可以多用

可以說,ThreadLocal是一把雙刃劍,用得來的話可以起到非常好的效果。但是,ThreadLocal如果用得不好,就會跟全局變量一樣。代碼不能重用,不能獨立測試。因為,一些本來可以重用的類,現在依賴于ThreadLocal變量。如果在其他沒有ThreadLocal場合,這些類就變得不可用了。個人覺得ThreadLocal用得很好的幾個應用場合,值得參考

1、存放當前session用戶:quake want的jert

2、存放一些context變量,比如webwork的ActionContext

3、存放session,比如Spring hibernate orm的session

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 九九热在线观看视频 | 久久久久嫩草影院精品 | 色国产精品 | 亚洲国产精品成 | 日本性生活免费看 | 亚洲免费在线观看视频 | 国产精品久久久久久久久免费 | 亚洲欧美专区精品久久 | 日韩成人在线视频 | 激情艳妇| 大学生宿舍飞机 free | 大奶妈咪女教师 | 国产专区视频在线观看 | 经典三级四虎在线观看 | 电车痴汉中文字幕 | 嫩草影院国产 | 精品一区二区三区波多野结衣 | 99热在这里只有精品 | 久久亚洲电影www电影网 | 美女脱了内裤让男桶爽 | 好大用力深一点女公交车 | 亚洲成人视屏 | 丝瓜视频在线观看污 | 97精品国产高清在线看入口 | 日日射视频| 国产欧美日韩高清专区ho | 国产成人v爽在线免播放观看 | 久久午夜夜伦痒痒想咳嗽P 久久无码AV亚洲精品色午夜麻豆 | 国产成人久视频免费 | 精精国产www视频在线观看免费 | 日本在线看免费 | 我半夜摸妺妺的奶C了她软件 | 韩国美女主播在线 | 古装一级无遮挡毛片免费观看 | 午夜福利电影网站鲁片大全 | 亚洲色图2 | 草莓丝瓜芭乐樱桃榴莲色多黄 | 天堂欧美 | 办公室操秘书 | 3d动漫h在线观看网站蜜芽 | 高h校花 |