ThreadLocal是线程本地变量的意思,即可以将变量控制在当前线程中,这样就避免了多线程并发的复杂处理,Spring中就有大量使用。
下面分析下常用的API。
ThreadLocal-set
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
set的时候,当threadLocals还未初始化时,将调用createMap方法初始化threadLocals(注意threadLocals是Thread的一个变量),然后将值放入threadLocals(一个ThreadLocal.ThreadLocalMap)。
ThreadLocal-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(); }
ThreadLocalMap getMap(Thread t) {
//拿到当前线程的threadLocals,是一个ThreadLocal.ThreadLocalMap return t.threadLocals; }
get的时候会拿到当前线程的threadLocals(是一个ThreadLocal.ThreadLocalMap),再根据key(即当前线程)获取相应的值。