InheritableThreadLocal用于子线程继承父线程的数值。将通过重写initialValue() 与childValue(Object parentValue)两个方法来展示例子。
其中initialValue()是InheritableThreadLocal类继承于ThreadLocal类的,用于初始化当前线程私有初始值,childValue(Object parentValue)是InheritableThreadLocal类的,作用是继承父线程的初始值并且进一步处理。
例子:
IhThreadLocal.Java
/**
* author:allenstarkx
* description:继承InheritableThreadLocal方法,并且重写初始化线程数值方法与修改子线程数值方法
*
*/
public class IhThreadLocal extends InheritableThreadLocal {
@Override
protected Object initialValue() {
return new Date().getTime();
}
@Override
protected Object childValue(Object parentValue) {
return parentValue+"已被修改";
}
}
IhThreadLocalUse.java
/**
* author:allenstarkx
* description:静态调用IhThreadLocal
*/
public class IhThreadLocalUse {
public static IhThreadLocal ihThreadLocal1 = new IhThreadLocal();
}
ThreadIH.java
/**
* author:allenstarkx
* description:输出子线程的IhThreadLocalUse的值
*/
public class ThreadIH extends Thread {
@Override
public void run() {
try{
for (int i = 0; i < 2; i++) {
System.out.println(IhThreadLocalUse.ihThreadLocal1.get());
Thread.sleep(100);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
IhThreadLocalTest.java
/**
* author:allenstarkx
* description:父线程输出IhThreadLocalUse的值与分两次创建子线程查看内IhThreadLocalUse的值
*/
public class IhThreadLocalTest {
public static void main(String[] args) {
try{
//情况1:在父类初始化IhThreadLocal前子线程先执行子线程
ThreadIH ih1 = new ThreadIH();
ih1.start();
//情况2:在父线程初始化IhThreadLocal后执行子线程
Thread.sleep(1000);
for (int i = 0; i < 2; i++) {
System.out.println("父线程"+IhThreadLocalUse.ihThreadLocal1.get());
}
ThreadIH ih2 = new ThreadIH();
ih2.start();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
先贴出运行结果
相关类说明在每个方法都有写明,以下是相关结论:
- 通过情况1和结果可以看出,子线程继承父线程值时,得父线程已经初始化过值后,否则子线程则自身调用initialValue()来初始化数值,并且不走childParent方法,此时与使用ThreadLocal(用于声明每个线程自身独有的值)无异。
- 子线程在父线程已经初始化值的情况下,不调用initiaValue()方法来初始化值,而是走childValue来返回数值,无论是否重写过该方法,因为该方法本身就是返回父线程的数值。下面是该方法的源码,可以看到是返回parentValue的值。