回顾方式
看源码
RequestContext->ThreadLocal->Thread->ThreadLocal.ThreadLocalMap
自己的归纳
- Thread中有个属性:
ThreadLocal.ThreadLocalMap threadLocals = null;
threadLocals
是哈希表,以不同的ThreadLocal实例为key,对应存储我们想要线程隔离的值。threadLocals
作为Thread的属性存储于Thread内部,但Thread自己不维护这个属性。其初始值为null,取值赋值皆由ThreadLocal实例去维护- ThreadLocal实例通过
Thread.currentThread()
找到Thread,进而获取到属于同一个包下
的Thread的threadLocals
,并以this
关键字将自己(ThreadLocal实例)
传入到threadLocals
中作为key设置或获取对应的值。- 所以,每个线程中有一个ThreadLocal.ThreadLocalMap属性,存储着各种不同的ThreadLocal实例,以及这些ThreadLocal实例对应的值。
ThreadLocal#get()
class ThreadLocal {
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T) e.value;
return result;
}
}
return setInitialValue();
}
}