一、前言
Thread类中,有一个属性,叫做:
ThreadLocal.ThreadLocalMap threadLocals;
这个属性,可以看出两个信息:ThreadLocal类和它的内部内ThreadLocalMap
下面,我们看一下这两个类。
1. ThreadLocal,直接上关键代码。
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();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
这个get方法的逻辑:(1)取出当前线程Thread,(2)通过getMap方法,取出当前Thread中的threadLocals属性,它是一个ThreadLocalMap。(3)根据当前的ThreadLocal对象,获取到ThreadLocalMap.Entry,并取出去其中的value,并返回。
2. set方法
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* Removes the current thread's value for this thread-local
* variable. If this thread-local variable is subsequently
* {@linkplain #get read} by the current thread, its value will be
* reinitialized by invoking its {@link #initialValue} method,
* unless its value is {@linkplain #set set} by the current thread
* in the interim. This may result in multiple invocations of the
* {@code initialValue} method in the current thread.
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
set方法很容易就能够明白,与Get方法是一对,set方法传入一个value对象,将其设置到当前线程的threadLocals当中。 在使用的时候,通过get()方法获取这个value。
小结:ThreadLocal最主要的三个方法,set、get、remove。调用set的时候,往当前线程对象的属性threadLocals当中添加键值对ThreadLocal-->V