class="java" name="code"> //可以存取线程局部变量 //先看构造函数 public ThreadLocal() { } //设置值 public void set(T value) { Thread t = Thread.currentThread(); //这个Map以this为key ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } //继承了WeakReference说明这个key是自动回收的 static class ThreadLocalMap { static class Entry extends WeakReference<ThreadLocal> { Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; } } private void set(ThreadLocal key, Object value) { Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1); for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal k = e.get(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); } //获取保存的值 public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); //有值则返回 if (e != null) return (T)e.value; } //返回初始化的值 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; } //覆盖这个方法获取初始值 protected T initialValue() { return null; } //删除值 public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); } /** 总结:ThreadLocal主要用于传递变量。如果要设置初始化的值可以直接覆盖initialValue()方法即可。 其原理是:将值存在一个ThreadLocalMap中。以自身为key,值为value。这个map继承了WeakReference。 说明其对于key是弱引用(相当于WeakHashMap)。 */