标签:
Thread类:通过代码发现当前Thread中有个变量ThreadLocalMap
1 ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal代码如下:
1 public T get() { 2 Thread t = Thread.currentThread(); 3 ThreadLocalMap map = getMap(t); 4 if (map != null) { 5 ThreadLocalMap.Entry e = map.getEntry(this); 6 if (e != null) 7 return (T)e.value; 8 } 9 return setInitialValue(); 10 }
1 ThreadLocalMap getMap(Thread t) { 2 return t.threadLocals; 3 }
1 static class Entry extends WeakReference<ThreadLocal> { 2 /** The value associated with this ThreadLocal. */ 3 Object value; 4 Entry(ThreadLocal k, Object v) { 5 super(k); 6 value = v; 7 } 8 }
这个变量是个map,这个Map中的Entry的key是ThreadLocal引用,value是Object,所以当前线程可以保存无数多个ThreadLocal变量,key是这个ThreadLocal的对象引用,value是保存的值。所以啊,在当前线程中就可以声明很多ThreadLocal进行存储当前线程需要的数据了。
标签:
原文地址:http://www.cnblogs.com/ruiding/p/4231351.html