ThreadLocal 理解
主要方法
public void set(T value); public T get(); private T setInitialValue(); public void set(T value) { Thread t = Thread.currentThread(); //得到当前线程 ThreadLocalMap map = getMap(t); //取得当前线程的ThreadLocalMap if (map != null) map.set(this, value); //设置当前Threadlocal的值 else createMap(t, value); } public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); //以当前线程的ThreadLocal为key 取得值 if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } private T setInitialValue() { T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); return value; }