学习过ThreadLocal的童鞋都知道,在子线程中,是无法访问父线程通过ThreadLocal设置的变量的。
package thread;
/**
* @author heyunlin
* @version 1.0
*/
public class ThreadLocalExample {
public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {
ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("hello");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run()...");
/*
* 子线程中无法访问父线程中设置的ThreadLocal变量
*/
System.out.println(threadLocal.get());
}
});
thread.start();
thread.join();
System.out.println(thread);
System.out.println(threadLocal.get());
}
}
运行结果:
InheritableThreadLocal就是为了解决这个不可见问题而生的~
package thread;
/**
* @author heyunlin
* @version 1.0
*/
public class InheritableThreadLocalExample {
public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {
InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
threadLocal.set("hello");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run()...");
System.out.println(threadLocal.get());
}
});
thread.start();
thread.join();
System.out.println(thread);
System.out.println(threadLocal.get());
}
}
运行结果: