public T get(){//首先得到当前线程
Thread t = Thread.currentThread();// 获取此线程对象中维护的ThreadLocalMap对象
ThreadLocalMap map =getMap(t);// 如果此map存在,以当前的ThreadLocal对象为key,调用map的getEntry获取Entry对象if(map != null){
ThreadLocalMap.Entry e = map.getEntry(this);if(e != null){// 如果entry对象不为空,获取entry对象的 value值
T result =(T)e.value;return result;}}// 如果map不存在,调用setInitialValue进行初始化returnsetInitialValue();}
ThreadLocald的setInitialValue()方法如下:
private T setInitialValue(){//首先获取初始值,initialValue()方法默认为null,用户可重写该方法
T value =initialValue();//得到当前线程
Thread t = Thread.currentThread();// 获取此线程对象中维护的ThreadLocalMap对象
ThreadLocalMap map =getMap(t);if(map != null)//如果map不为空,则设置初始值
map.set(this, value);else//如果map为空,则创建ThreadLocalMap对象并将value存至mapcreateMap(t, value);return value;}
private Entry getEntry(ThreadLocal<?> key){int i = key.threadLocalHashCode &(table.length -1);
Entry e = table[i];if(e != null && e.get()== key)return e;elsereturngetEntryAfterMiss(key, i, e);}
在以上代码中,首先计算key对应的entry对象的存储位置,然后根据位置在数组中拿到entry对象,如果entry对象不为null并且entry的key与方法中传入的key相同,则返回entry对象,否则执行getEntryAfterMiss(key, i, e)方法,在此方法中,对数组中元素进行遍历,如果entry对象的key不为null,则与传入的key进行比较,相同则返回此entry对象;如果entry对象的key为null,说明该对象已过期,则调用expungeStaleEntry方法清除过期对象。