Thread name:main<-->main thread. Thread name:Thread one<-->This is thread one. Thread name:Thread two<-->This is thread two. Thread name:Thread three<-->This is thread three.
Java实现过程
set方法实现过程
尝试获取或创建ThreadLocalMap
1 2 3 4 5 6 7 8 9
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { map.set(this, value); } else { createMap(t, value); } }
创建ThreadLocalMap并赋值个ThreadLocal私有变量
1 2 3 4 5 6 7 8 9 10
/** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the map */ void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
获取一个ThreadLocalMap
1 2 3 4 5 6 7 8 9 10 11
/** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }