ThreadLocal的设计思想十分简单,它的核心对象就是ThreadLocalMap,被声明在Thread类里面,每个Thread都持有一个ThreadLocalMap,所以才能实现线程隔离,以达到存储共享变量的作用:
ThreadLocal.ThreadLocalMap threadLocals = null;
对ThreadLocalMap的所有操作都在ThreadLocal类里面,我认为ThreadLocal本身其实只是个工具类,ThreadLocalMap 才是共享变量在线程中的副本的存在。下面是ThreadLocal中对线程的ThreadLocalMap 的操作:
//设置当前线程的共享变量的值,key为ThreadLocal对象本身,value为共享变量的值
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}```
//获取当前线程的共享变量的值
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();
}`
//得到线程的ThreadLocalMap对象
return t.threadLocals;
}```
//为一个线程创建一个ThreadLocalMap对象
t.threadLocals = new ThreadLocalMap(this, firstValue);
}`
我们来说说ThreadLocalMap这个对象,它是一个hashmap结构,每个key和value都构成一个Entry,这个Entry继承了弱引用:
/** The value associated with this ThreadLocal.**/
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}```