一、Thread
public class Thread(){ //省略部分 //属于这个线程的ThreadLocals,这个map由ThreadLocal类维护 ThreadLocal.ThreadLocalMap threadLocals = null; //省略部分 }
二、ThreadLocal
public class ThreadLocal(){ //省略部分 //set操作 public void set(T value) { //当前调用set方法的线程 Thread t = Thread.currentThread(); //获取当前调用线程的ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) //this 为静态的一个自定义的ThreadLocal对象的引用,map存在则set map.set(this, value); else //map 不存在则新建 createMap(t, value); } // new 一个ThreadLocalMap void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } // get操作 public T get() { //当前调用get方法的线程 Thread t = Thread.currentThread(); //获取当前线程的ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) { //this 为静态的一个自定义的ThreadLocal对象的引用 ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } //省略部分 }