ThreadLocal 是java.lang 包下的一个类。
前提:ThreadLocal里面有一个静态内部类 ThreadLocalMap
先看get方法
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();
}
得到当前线程对象,getMap()方法是得到当前线程对象的ThreadLocalMap对象(Thread类也有ThreadMap这个属性)
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
一句话总结:ThreadLocal 得到当前线程的ThreadLocalMap属性,然后对这个属性进行读取,写入和删除操作;