![](/img/trans.png)
[英]InheritableThreadLocal variable value not inherited by child thread
[英]How does InheritableThreadLocal work for instance variable thread?
我有以下程序
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。為什么會這樣?
來自 API 文檔:
創建子線程時,子線程接收父線程具有值的所有可繼承線程局部變量的初始值。
讓我們在不改變任何實現的情況下重寫ParentThread
以使其更加明確。 (完全沒有特別的理由在演示中使用ParentThread
- 主線程會做得很好。編輯:我應該繼續這個想法ChildThread
實例從主線程繼承可繼承的線程ParentThread
,而不是ParentThread
實例。 )
class ParentThread extends Thread{
static InheritableThreadLocal tl;
static {
tl = new InheritableThreadLocal();
}
/* pp */ ChildThread c;
public ParentThread(String s) {
super(s);
this.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();
}
}
我們看到ChildThread
構造函數在InheritableThreadLocal.set
之前被調用。 在tl.set(pp);
之后寫new ChildThread()
tl.set(pp);
並且應該看到它的價值。
InheritableThreadLocal
很瘋狂。 除非做一些惡意的事情,否則我會避免它。
一般來說,我強烈建議避免不必要的子類化和ThreadLocal
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.