和ThreadLocal相比,在子线程中也可以使用
方法
这个类很简单,继承了ThreadLocal,重写了三个方法
“`
protected T childValue(T parentValue) {
return parentValue;
}
// InheritableThreadLocal也是Thread的一个属性
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
//只不过是把threadLocal赋值给Thread的inheritableThreadLocals
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
“`
线程传递的实现
Thread类中的构造函数会调用init方法,init方法中会处理inheritableThreadLocal
“`
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
............................中间省略
Thread parent = currentThread();
............................中间省略
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
............................中间省略
}
“`
实现也很简单,将父线程的inheritableThreadLocals赋值给子线程的inheritableThreadLocals