一般用法:
class Test{
public static ThreadLocal test = new ThreadLocal();
public static String getThreadLocalTest(){
return test.get();
}
public static void setThreadLocalTest(String value){
test.set(value);
}
}
当test.set(value)给ThreadLocal变量值时, 低层方法实现:将当前的ThreadLocal实例做为key, 将值做为value,做为Map, 跟当前线程绑定的, 在代码的其他的地方, 可以直接Test.getThreadLocalTest(),获取当前线程的ThreadLocal为key的值
1、ThreadLocal类中的代码
public void set(T value) {
Thread t = Thread.currentThread();
//取得当前线程的ThreadLocal的内部类ThreadLocalMap
ThreadLocalMap map = getMap(t);
//如果有值, 修改, 如果没有,
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
return (T)map.get(this);
// Maps are constructed lazily. if the map for this thread
// doesn't exist, create it, with this ThreadLocal and its
// initial value as its only entry.
T value = initialValue();
createMap(t, value);
return value;
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
2、Thread类
publicclass Thread implements Runnable {
......
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
//Thread类中有一个属性是:ThreadLocalMap,与当前线程绑定的值
ThreadLocal.ThreadLocalMap threadLocals = null;
......
}