之前面试的时候,当谈到ThreadLocal时,被人问到,在子线程中如何获取父线程的ThreadLocal里面存储的变量。今天看到了一个类InheritableThreadLocal才明白原来是这样来做的。
先来看一下InheritableThreadLocal的源码。
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
/**
* Computes the child's initial value for this inheritable thread-local
* variable as a function of the parent's value at the time the child
* thread is created. This method is called from within the parent
* thread before the child is started.
* <p>
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
*
* @param parentValue the parent thread's value
* @return the child thread's initial value
*/
protected T childValue(T parentValue) {
return parentValue;
}
/**
* Get the map associated with a ThreadLocal.
*