【发布时间】:2020-11-06 05:07:30
【问题描述】:
我有以下程序
class ParentThread extends Thread{
public ParentThread(String s) {
super(s);
}
static InheritableThreadLocal tl = new InheritableThreadLocal();
ChildThread c = new ChildThread("child");
@Override
public void run() {
tl.set("pp");
System.out.println("Thread :"+Thread.currentThread().getName()+" thread local value: "+tl.get());
c.start();
}
}
class ChildThread extends Thread{
public ChildThread(String child) {
super(child);
}
@Override
public void run() {
System.out.println("Thread :"+Thread.currentThread().getName()+" thread local value: "+ParentThread.tl.get());
}
}
public class ThreadLocalDemo {
public static void main(String[] args) {
ParentThread p = new ParentThread("parent");
p.start();
}
}
我得到的输出为
Thread :parent thread local value: pp
Thread :child thread local value: null
我相信即使我将 ChildThread 声明为实例变量,父线程的 run 方法也负责创建子线程。那么,为什么孩子的输出为空?
当我放这个
ChildThread c = new ChildThread("child");
在run方法里面,我确实得到了pp。为什么会这样?
【问题讨论】:
标签: java multithreading thread-local