1.直接上测试代码
public class ThreadlocalTest extends Thread{
public static ThreadLocal threadLocal=new ThreadLocal();
private String name;
public ThreadlocalTest(String name){
this.name=name;
}
@Override
public void run() {
threadLocal.set(currentThread().getName()+"+++++++"+name);
System.out.println(threadLocal.get());
}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new ThreadlocalTest("thread"+i).start();
}
}
}
运行结果:
每个线程都只是get自己的值。
上源码 ThreadLocal.java
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
真正存数据的事ThreadLocalMap,而且他是当前线程自己的,看这个getMap(t),他就是Thread这个类的一个成员变量,在第一次set的时候进行初始化
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
继续看createMap(t,value)
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);
//这里key就是当前threadLocal对象,value是要保存的值
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
ThreadLocalMap是ThreadLocal的衣蛾内部类,可以理解为是一个hashmap
get()方法
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;
}
}
return setInitialValue();
}
总结:ThreadLocal就是给每一个线程创建一个ThreadLocalMap,用于保证各自线程get的值都是自己set的