//获取当前Thread的threadLocalMap变量,以ThreadLocal为key,从threadLocalMap中取值 public T get(){ Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } //当线程对应ThreadLocalMap未存储该key时,返回null return setInitialValue(); } ThreadLocalMap getMap(Thread t){ return t.threadLocals; }
voidcreateMap(Thread t, T firstValue){ t.threadLocals = new ThreadLocalMap(this, firstValue); }
}
1 2
Entry[] tab = table; tab[i] = new Entry(key, value);
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassThreadLocal<T> {
...
staticclassThreadLocalMap{ ...
privatestaticintnextIndex(int i, int len){ return ((i + 1 < len) ? i + 1 : 0); }
privatestaticvoidprepare(boolean quitAllowed){ //每个线程只允许执行一次该方法,第二次执行时线程的TLS已有数据,则会抛出异常。 if (sThreadLocal.get() != null) { thrownew RuntimeException("Only one Looper may be created per thread"); } //创建Looper对象,并保存到当前线程的TLS区域 sThreadLocal.set(new Looper(quitAllowed)); }