1.get()方法
/**
* 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() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
第一步先获取到当前的线程
第二步通过getmap获取到当前线程的threadLocals变量。
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
在Thread中是这么定义的
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
返回的是一个 ThreadLocal中的ThreadLocalMap对象,并且没有任何修饰符,由于ThreadLocal和Thread都属于 package java.lang; 所以这两个可以互相访问
ThreadLocalMap中有这个对象,这里使用了弱引用。弱引用在没人其他变量指向它时就会释放。(