ThreadLocalMap是Thread类的一个成员变量,所以一个Thread对应了一个ThreadLocalMap。一个ThreadLocalMap里面可以多个以ThreadLocal对象为key的键值对。
threadLocal.get()方法
public T get() { //1、先获取当前线程 Thread t = Thread.currentThread(); //2、获取该线程的ThreadLocalMap对象 ThreadLocalMap map = getMap(t); if (map != null) { //3、根据当前threadLocal对象为key去获取值 ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } //如果改线程的ThreadLocalMap为空就会去setInitialValue()方法中获取initialValue()中默认的值,如果不重写该方法则返回null return setInitialValue(); } //setInitialValue()方法源码如下: private T setInitialValue() { //initialValue()没重写默认return null T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { map.set(this, value); } else { createMap(t, value); } if (this instanceof TerminatingThreadLocal) { TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this); } return value; }threadLocal.set(T value)方法:
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { map.set(this, value); } else { createMap(t, value); } }threadLocal.remove()
public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) { m.remove(this); } }