1 ThreadLocal.class 2 /** 3 * Sets the current thread's copy of this thread-local variable 4 * to the specified value. Most subclasses will have no need to 5 * override this method, relying solely on the {@link #initialValue} 6 * method to set the values of thread-locals. 7 * 8 * @param value the value to be stored in the current thread's copy of 9 * this thread-local. 10 */ 11 public void set(T value) { 12 Thread t = Thread.currentThread(); 13 //根据线程局部变量ThreadLocal实例来获取与之对应的ThreadLocalMap实例 14 ThreadLocalMap map = getMap(t); 15 if (map != null) 16 //如果ThreadLocalMap 不为null,那么就以ThreadLocal为key,以value为值,进行绑定 17 map.set(this, value); 18 else 19 /** 20 *如果根据当前的线程局部变量没有获取到与之绑定的ThreadLocal.ThreadLocalMap实例, 21 *那么就创建一个 ThreadLocal.ThreadLocalMap实例 22 *且以当前的线程为 key,传入的绑定值 为 value 23 * 24 */ 25 createMap(t, value); 26 } 27 28 29 30 ThreadLocal.class 31 32 // 在ThreadLocal.java的 224行 33 /** 34 * Create the map associated with a ThreadLocal. Overridden in 35 * InheritableThreadLocal. 36 * 37 * @param t the current thread 38 * @param firstValue value for the initial entry of the map 39 * @param map the map to store. 40 */ 41 void createMap(Thread t, T firstValue) { 42 //这一段代码就把当前线程与 ThreadLocal(下面一行代码里的this就是 ThreadLocal)以及要绑定的值 关联了起来 43 t.threadLocals = new ThreadLocalMap(this, firstValue); 44 } 45 46 47 Thread.class的180行 48 49 /* ThreadLocal values pertaining to this thread. This map is maintained 50 * by the ThreadLocal class. */ 51 ThreadLocal.ThreadLocalMap threadLocals = null; 52 /* 53 *通过 Thread类的180行的这行代码我们可以知道,每个线程实例都有一个 54 * 类型为 ThreadLocal.ThreadLocalMap 的threadLocals属性, 55 * 这个属性的一个很重要的作用就是 接收 在ThreadLocal.java的224行的 56 * 方法 createMap(Thread t,T firstValue)里 new的TheadLocalMap变量 57 */ 58 ThrealLocal.ThreadLocalMap.class 59 60 /** 61 * Construct a new map initially containing (firstKey, firstValue). 62 * ThreadLocalMaps are constructed lazily, so we only create 63 * one when we have at least one entry to put in it. 64 * 这里是 ThrealLocal.ThreadLocalMap 构造器, 65 */ 66 ThreadLocalMap(ThreadLocal firstKey, Object firstValue) { 67 table = new Entry[INITIAL_CAPACITY]; 68 int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); 69 table[i] = new Entry(firstKey, firstValue); 70 size = 1; 71 setThreshold(INITIAL_CAPACITY); 72 } 73 74 75 76 77 78 ThreadLocal.class 79 /** 80 * Returns the value in the current thread's copy of this 81 * thread-local variable. If the variable has no value for the 82 * current thread, it is first initialized to the value returned 83 * by an invocation of the {@link #initialValue} method. 84 * 85 * @return the current thread's value of this thread-local 86 */ 87 public T get() { 88 Thread t = Thread.currentThread(); 89 ThreadLocalMap map = getMap(t); 90 if (map != null) { 91 ThreadLocalMap.Entry e = map.getEntry(this); 92 if (e != null) 93 return (T)e.value; 94 } 95 return setInitialValue(); 96 }