類ThreadLocal的使用
變量值的共享可以使用public static變量的形式實現,所有的線程都使用同一個public static變量,那如何實現每一個線程都有自己的變量呢?JDK提供的ThreadLocal可用於解決這樣的問題。
類ThreadLocal主要解決的就是每個線程綁定自己的值,可以將ThreadLocal類比喻成全局存放數據的盒子,盒子中可以存儲每個線程的私有數據。
類ThreadLocal解決的是不同線程之間的隔離性,也就是不同線程擁有自己的值,不同線程中的值是可以放入ThreadLocal進行保存的。
- 在第一次調用ThreadLocal類的get()方法返回值是null,怎麼實現第一次調用get()不返回null呢?
解決辦法:
public class ThreadLocalExt extends ThreadLocal{
@Override
protected Object initialValue() {
return "我是默認值,第一次get()不再爲null";
}
}
創建測試類RunTest:
public class RunTest {
public static ThreadLocalExt t2 = new ThreadLocalExt();
public static void main(String[] args) {
System.out.println(t2.get());
if(t2.get() == null){
System.out.println("從未放過誰");
t2.set("我的值");
}
System.out.println(t2.get());
}
}
-
驗證ThreadLocal線程變量的隔離性
創建類ThreadA:
public class ThreadA extends Thread{
@Override
public void run() {
try {
for (int i = 0; i < 2; i++){
System.out.println("在ThreadA線程中取值="+Tools.t1.get());
Thread.sleep(100);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
其中:工具類Tools:
public class Tools {
public static ThreadLocalExt t1 = new ThreadLocalExt();
}
ThreadExt類:
public class ThreadLocalExt extends ThreadLocal{
@Override
protected Object initialValue() {
return new Date().getTime();
}
}
最後的測試類爲:
public class RunTest {
public static void main(String[] args) {
try {
for(int i = 0; i < 2; i++){
System.out.println("在Main線程中取值="+Tools.t1.get());
Thread.sleep(100);
}
Thread.sleep(5000);
ThreadA a = new ThreadA();
a.start();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
運行結果輸出爲:在Main線程和在ThreadA線程中是不一樣的值
在Main線程中取值=1592824018145
在Main線程中取值=1592824018145
在ThreadA線程中取值=1592824023353
在ThreadA線程中取值=1592824023353
類InheritableThreadLocal的使用
InheritableThreadLocal可以在子線程中取得父線程的值:
修改ThreadLocalExt爲下圖:
public class ThreadLocalExt extends InheritableThreadLocal{
@Override
protected Object initialValue() {
return new Date().getTime();
}
}
運行上面的RunTest類,運行結果如下:
在Main線程中取值=1592825297723
在Main線程中取值=1592825297723
在ThreadA線程中取值=1592825297723
在ThreadA線程中取值=1592825297723
如果繼承了之後想要對值進行進一步的修改處理:
修改ThreadLocalExt爲下面的圖:
public class ThreadLocalExt extends InheritableThreadLocal{
@Override
protected Object initialValue() {
return new Date().getTime();
}
@Override
protected Object childValue(Object parentValue) {
return parentValue+"在子線程中加的值!";
}
}
運行結果爲下:
在Main線程中取值=1592825542006
在Main線程中取值=1592825542006
在ThreadA線程中取值=1592825542006在子線程中加的值!
在ThreadA線程中取值=1592825542006在子線程中加的值!
但在使用InheritableThreadLocal類需要注意的一點是:如果子線程在取得值的同時,主線程將InheritableThreadLocal中的值進行更改,那麼子線程取到的值還是舊值。