/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() { Threadt= Thread.currentThread(); ThreadLocalMapmap= getMap(t); if (map != null) { ThreadLocalMap.Entrye= map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") Tresult= (T)e.value; return result; } } return setInitialValue(); }
但是这里有个问题,如果是子线程,就访问不到了
我们深入源码看到这里有这么一个函数
1 2 3 4 5 6 7 8 9 10 11
/** * Method childValue is visibly defined in subclass * InheritableThreadLocal, but is internally defined here for the * sake of providing createInheritedMap factory method without * needing to subclass the map class in InheritableThreadLocal. * This technique is preferable to the alternative of embedding * instanceof tests in methods. */ T childValue(T parentValue) { thrownewUnsupportedOperationException(); }