image.png
ThreadLocalMap是所有ThreadLocal所共有的(静态内部类),每个线程根据自己的线程ID去这个Map里面取值

我们不可以直接调用ThreadLocalMap,必须通过ThreadLocal来调用

Set方法

  1. public void set(T value) {
  2. Thread t = Thread.currentThread();
  3. ThreadLocalMap map = getMap(t);
  4. if (map != null)
  5. map.set(this, value);
  6. else
  7. createMap(t, value);
  8. }

Get方法

  1. public T get() {
  2. Thread t = Thread.currentThread();
  3. ThreadLocalMap map = getMap(t);
  4. if (map != null)
  5. return (T)map.get(this);
  6. // Maps are constructed lazily. if the map for this thread
  7. // doesn't exist, create it, with this ThreadLocal and its
  8. // initial value as its only entry.
  9. T value = initialValue();
  10. createMap(t, value);
  11. return value;
  12. }