类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中的值进行更改,那么子线程取到的值还是旧值。