ThreadLocal在子线程中的访问
当一个线程T定义一个ThreadLocal局部变量,在线程T下再创建一个子线程T1,那么T1访问不到ThreadLocal
ThreadLocal使用的是Map,每个线程中有一个Map结构,初始化Map并和此线程绑定
public class A{
static int a = 5;
public static void main(String[] args) {
int b = 7;
new Thread(new Runnable() {
ThreadLocal<String> thread = new ThreadLocal<String>();
@Override
public void run() {
thread.set("hello");
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(String.format("inner thread :)%s", thread.get()));
System.out.println(String.format("inner a :)%s", a));
System.out.println(String.format("inner b :)%s", b));
}
}).start();
System.out.println(String.format("outer thread :)%s", thread.get()));
System.out.println(String.format("outer a :)%s", a));
System.out.println(String.format("outer b :)%s", b));
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
输出结果为:
inner thread :)null inner a :)5 inner b :)7 outer thread :)hello outer a :)5 outer b :)7
说明子线程访问不到父线程的局部变量ThreadLocal
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(Thread t) {
return t.threadLocals;
}
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();
}
每个线程都有与之对应的Map,,每次new一个ThreadLocal,都会在与之对应的Map中添加一条记录
map.set(this, value);
其中的key为当前new ThreadLocal()对象本身变量,value为当前ThreadLocal设置的值
一个线程可以创建多个局部变量,那么Map中就可能存储多条ThreadLocal
浙公网安备 33010602011771号