一般来说,变量可以被不同线程读写,但是ThreadLocal只有当前线程可以读写,就像多进程一样,不同线程之间访问同一个ThreadLocal变量是完全独立互不干扰的;
先上源码(截取部分内容):
public class Thread implements Runnable{
...
ThreadLocal.ThreadLocalMap threadLocals = null;
...
}
public class ThreadLocal<T>{
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T) e.value;
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t){
return t.threadLocals;
}
}
分析:
上述内容非常容易理解,每新建一个Thread就会在新Thread中保留着ThreadLocalMap实例,而从ThreadLocal中get value则会从当前的Thread中去获取threadLocals变量,从中取值。以此实现ThreadLocal在各自线程中独立保存value的功能;