ThreadLocal不是线程,ThreadLocal实现原理就是在ThreaLocal内部定义了一个ThreadLocalMap的内部类,而现在又持有ThreadLoca.ThreadlocalMap对象属性,通过ThreadLocal存值和取值其实都是拿去线程上ThreadLocal.ThreadLocalMap属性的值或为其设置值。
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, 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(); }
public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }
public class Thread implements Runnable { ThreadLocal.ThreadLocalMap threadLocals = null;
}