val threadLocal= ThreadLocal<Any>()
threadLocal.set("hhahah")
threadLocal.get()
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
1.可见是由map中取值,如果getMap(t)存在则直接set,否者则创建
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
2.getmap() 是从当前线程中取出自己的 ThreadLocalMap
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
3.可知ThreadLocalMap里面是一个散列表,下标是ThreadLocal, 值是set里面的value
4.至此set跟踪完毕,由此可知, ThreadLocal的set实际上是,
初始化了当前线程的threadLocals,并且把值通过散列表存入自己内部
5.每一个ThreadLocal 都是线程里面散列表的下标