一、ThreadLocal回顾
ThreadLocal对象用于在同一个线程中传递数据,避免显式的在方法中传参。
每个线程中保存了ThreadLocalMap对象,ThreadLocalMap对象的key就是ThreadLocal对象本身,value就是当前线程的值。
看下ThreadLocal的get方法
public T get() { //当前线程 Thread t = Thread.currentThread(); //获取当前线程的ThreadLocalMap对象 ThreadLocalMap map = getMap(t); if (map != null) { //获取该ThreadLocal对象的value ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } //设置初始值 return setInitialValue(); } //获取当前线程的ThreadLocalMap对象 ThreadLocalMap getMap(Thread t) { return t.threadLocals; }