ThreadLocal的使用及原理解析( 二 )


//    从指定线程对象获取ThreadLocalMap,也就是Thread中的threadLocalsThreadLocalMap getMap(Thread t) {    return t.threadLocals;}
//    默认值private T setInitialValue() {    T value = https://www.huyubaike.com/biancheng/initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value);// 如果当前线程的threadLocals不为null,则赋默认值 else createMap(t, value); // 如果当前线程的threadLocals为null,则新建 return value;}
void createMap(Thread t, T firstValue) {    t.threadLocals = new ThreadLocalMap(this, firstValue);}
protected T initialValue() {    return null;  //  初始值是null}
```
从以上这段代码可以看出,ThreadLocal访问的实际上是当前线程的成员变量threadLocals 。<br />threadLocals的数据类型是ThreadLocalMap,这是JDK中专门为ThreadLocal设计的数据结构,它本质就是一个键值对类型 。<br />ThreadLocalMap的键存储的是当前ThreadLocal对象,值是ThreadLocal对象实际存储的值 。<br />当用ThreadLocal对象get方法时,它实际上是从当前线程的threadLocals获取键为当前ThreadLocal对象所对应的值 。
画张图来辅助一下理解:<br />![](https://cdn.nlark.com/yuque/0/2022/jpeg/2565452/1667566447745-4dac46dc-c1ad-4a10-b62b-5d9a8506c8fa.jpeg)
清楚了ThreadLocal的get原理,set和remove方法不需要看源码也能猜出是怎么写的 。<br />无非是以ThreadLocal对象为键设置其值或删除键值对 。
# ThreadLocal的初始值
上面的介绍,我们看到ThreadLocal的initialValue方法永远都是返回null的:```javaprotected T initialValue() {    return null;  //  初始值是null}```
如果想要设定ThreadLocal对象的初始值,可以用以下方法:```javaThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->1);System.out.println(threadLocal.get());```withInitial方法内实际返回的是一个ThreadLocal子类SuppliedThreadLocal对象 。<br />SuppliedThreadLocal重写了ThreadLocal的initialValue方法 。```javastatic final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {        this.supplier = Objects.requireNonNull(supplier);    }
@Override    protected T initialValue() {        return supplier.get();    }}```
# 获取父线程的ThreadLocal变量
在一些场景下,我们可能需要子线程能获取到父线程的ThreadLocal变量,但使用ThreadLocal是无法获取到的:```javapublic static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {    threadLocal.set(1);    System.out.println(threadLocal.get());
Thread childThread = new Thread(() -> System.out.println(threadLocal.get()));    childThread.start();}```输出:```powershell1null```
使用ThreadLocal的子类**InheritableThreadLocal**可以达到这个效果:```javapublic static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {    threadLocal.set(1);    System.out.println(threadLocal.get());
Thread childThread = new Thread(() -> System.out.println(threadLocal.get()));    childThread.start();}``````powershell11```
**InheritableThreadLocal是怎么做到的呢?**
我们来分析一下InheritableThreadLocal的源代码 。```javapublic class InheritableThreadLocal<T> extends ThreadLocal<T> {        protected T childValue(T parentValue) {        return parentValue;    }

经验总结扩展阅读