主线程如何向自己创建的子线程传递ThreadLocal值,只需要创建InheritableThreadLocal值,实现原理如下:
InheritableThreadLocal覆写了它三个方法:
1 | public class InheritableThreadLocal<T> extends ThreadLocal<T> { |
见子线程初始化过程,初始化时候如果当前线程inheritableThreadLocals不为空
1 | private void init(ThreadGroup g, Runnable target, String name, |
那么inheritableThreadLocals它什么时候不为空呢,见下面:
1 | //在set值时候判断ThreadLocalMap为空,调用InheritableThreadLocal.getMap方法返回当前线程的t.inheritableThreadLocals,否则初始化t.inheritableThreadLocals |