在前面文章中我们已经通过ThreadLocal来实现线程级别的数据共享。那么如果子线程想访问父线程的数据该怎么做呢,InheritableThreadLocal可以帮助我们实现
1 InheritableThreadLocal的使用
测试代码
private InheritableThreadLocal<Integer> inheritableThreadLocalData = new InheritableThreadLocal<>();
private ThreadLocal<Integer> threadLocalData = new ThreadLocal<>();
@Test
public void testInheritableThreadLocal() throws InterruptedException, ExecutionException {
inheritableThreadLocalData.set(1);
threadLocalData.set(1);
System.out.println("current thread get InheritableThreadLocal data:" + inheritableThreadLocalData.get() +
" get ThreadLocal data:" + threadLocalData.get());
new Thread(() -> System.out.println("son thread get InheritableThreadLocal data:" + inheritableThreadLocalData.get() +
" get ThreadLocal data:" + threadLocalData.get())).start();
}
输出
current thread get InheritableThreadLocal data:1 get ThreadLocal data:1
son thread get InheritableThreadLocal data:1 get ThreadLocal data:null
可以看到当前内是可以访问到ThreadLocal和InheritableThreadLocal的数据的
子线程只能访问InheritableThreadLocal的数据,不能访问ThreadLocal的数据
2 InheritableThreadLocal原理
InheritableThreadLocal继承了ThreadLocal类,get、set方法用的都是父类的方法,只是重写了getMap和createMap
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
inheritableThreadLocals也是ThreadLocal.ThreadLocalMap对象,正常来说InheritableThreadLocal和ThreadLocal的功能完全一致的,那么为什么前者可以获取到父线程的值,后者不能呢?
我们看一下Thread的构造方法
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
直接跟到最下面
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
关键就在这段代码
// parent就是父线程,也就是执行new Thread()的线程
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
这里会把父线程的inheritableThreadLocals赋值给子线程,从而实现了父子线程变量传递