ThreadLocal原理:
每个Thread都有一个内部类ThreadLocal.ThreadLocalMap threadLocals,ThreadLocalMap 有内部类Entry
ThreadLocal通过线程来获取ThreadLocalMap(返回当前线程的threadLocals),ThreadLocalMap又通过TheadLocal对象来获取Entry,进而得到value(好像Entry中有一个key和一个value,key是ThreadLocal对象,value是就是要存储的值,但是这样理解并不准确)
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) {
return t.threadLocals;
}
public class ThreadLocal<T> {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
public class WeakReference<T> extends Reference<T> {
public WeakReference(T referent) {
super(referent);
}
}
ThreadLocal通过线程来获取ThreadLocalMap(返回当前线程的threadLocals),ThreadLocalMap将ThreadLocal对象和value保存进Entry
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);
}