ThreadLocal
public class MyThread extends Thread {
private ThreadLocal<String> threadLocal = new ThreadLocal<>();
public void run() {
threadLocal.set("ThreadLocal value in MyThread");
System.out.println("MyThread: " + threadLocal.get());
Thread childThread = new Thread() {
public void run() {
System.out.println("ChildThread: " + threadLocal.get());
}
};
childThread.start();
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
MyThread: ThreadLocal value in MyThread
ChildThread: null
InheritableThreadLocal
public class MyThread extends Thread {
private ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
public void run() {
threadLocal.set("ThreadLocal value in MyThread");
System.out.println("MyThread: " + threadLocal.get());
Thread childThread = new Thread() {
public void run() {
System.out.println("ChildThread: " + threadLocal.get());
}
};
childThread.start();
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
MyThread: ThreadLocal value in MyThread
ChildThread: ThreadLocal value in MyThread
TransmittableThreadLocal
同 InheritableThreadLocal
标签:ThreadLocal,Thread,MyThread,threadLocal,举例,InheritableThreadLocal,使用,new,public From: https://www.cnblogs.com/sunupo/p/18053996