1、get()方法
(1)获取当前用的线程,并找到线程关联的threadlocalmap
(2)threadlocalmap为空则进行初始化一个新的并返回
(3)threadlocalmap不为空则根据threadlocal作为key查找entry
(4)若entry不为空则返回entry对应的值,否则执行第二条
public t get() { // 获取当前线程 thread t = thread.currentthread(); threadlocalmap map = getmap(t); //若当前线程关联的threadlocal不为空则查询 if (map != null) { //根据threadlocal查询对应的entry threadlocalmap.entry e = map.getentry(this); if (e != null) { @suppresswarnings(unchecked) t result = (t)e.value; return result; } } return setinitialvalue();} private t setinitialvalue() { //默认返回null值 t value = initialvalue(); thread t = thread.currentthread(); threadlocalmap map = getmap(t); //如果当前调用线程关联的threadlocalmap为空则创建,否则设置值进去 if (map != null) map.set(this, value); else //new threadlocalmap(this,value) createmap(t, value); return value; } private entry getentry(threadlocal<?> key) { //根据key获取其在数组的下标位置 int i = key.threadlocalhashcode & (table.length - 1); entry e = table[i]; if (e != null && e.get() == key) return e; else return getentryaftermiss(key, i, e);} private entry getentryaftermiss(threadlocal<?> key, int i, entry e) { entry[] tab = table; int len = tab.length; //数组下标的entry不为空且关联的threadlocal与查找的threadlocal不一致 while (e != null) { threadlocal<?> k = e.get(); //entry关联的threadlocal与查找的相等则直接返回 if (k == key) return e; if (k == null) //关联的threadlocal为空,则触发清理key为null的entry并重新进行rehash旧entry数组的元素 //threadlocalmap的hash冲突与hashmap的冲突处理方式不一致,hashmap使用的是链表地址法, //而threadlocalmap使用的开放地址法——线性探测,即顺序查找下一位置或者遍历全表,效率较低 expungestaleentry(i); else //递增下标i的值进行下一轮的查找 i = nextindex(i, len); e = tab[i]; } return null;}
2、remove()方法
(1)获取当前用的线程,并找到线程关联的threadlocalmap
(2)若不为空则删除threadlocalmap中关联的值,否则啥也不做
//threadlocalpublic void remove() { threadlocalmap m = getmap(thread.currentthread()); if (m != null) //删除当前threadlocal对象关联的entry m.remove(this);} //threadlocalmapprivate void remove(threadlocal<?> key) { entry[] tab = table; int len = tab.length; int i = key.threadlocalhashcode & (len-1); for (entry e = tab[i]; e != null; e = tab[i = nextindex(i, len)]) { if (e.get() == key) { e.clear(); expungestaleentry(i); return; } }}
以上就是java中threadlocal核心方法怎么使用的详细内容。