我们都知道线程本地变量表也就是ThreadLocal在我们做线程级的数据隔离时非常好用,但是有时候我们会想如何让子线程获取到父线程的ThreadLocal,其实在线程中除了ThreadLocal外还有InheritableThreadLocal,顾名思义,可继承的线程变量表,可以让子线程获取到父线程中ThreadLocal的值。
public class BaseTest { public static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>(); public static final ThreadLocal<String> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { inheritableThreadLocal.set("Inheritable hello"); threadLocal.set("hello"); new Thread(()->{ System.out.println(String.format("子线程可继承值:%s",inheritableThreadLocal.get())); System.out.println(String.format("子线程值:%s",threadLocal.get())); new Thread(()->{ System.out.println(String.format("孙子线程可继承值:%s",inheritableThreadLocal.get())); System.out.println(String.format("孙子线程值:%s",threadLocal.get())); }).start(); }).start(); }
执行后获取返回值。
可以看到不可继承的ThreadLocal子线程是不能共享父线程的。可继承的ThreadLocal如何实现呢?
其原理和ThreadLocal基本上一致,都是线程中存有ThreadLocalMap
/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; /* * InheritableThreadLocal values pertaining to this thread. This map is * maintained by the InheritableThreadLocal class. */ ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
我们在new线程时init方法会有如下操作。
Thread parent = currentThread(); ../省略代码 if (inheritThreadLocals && parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
如果允许使用继承当前线程的本地变量变,那么new的线程copy当前线程也就是父线程的inheritableThreadLocals 。这儿也可以说明继承有两条件,new的线程允许继承(默认允许),父线程的inheritableThreadLocals 不为null。
**这儿要注意不管是创建ThreadLocal还是inheritableThreadLocals 的ThreadLocalMap大多都是在Threadlocal.set方法的时候创建的,即懒加载。
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
来源:https://www.cnblogs.com/hetutu-5238/p/12461605.html