引出结论
学习过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() {@Overridepublic 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() {@Overridepublic void run() {System.out.println("run()...");System.out.println(threadLocal.get());}});thread.start();thread.join();System.out.println(thread);System.out.println(threadLocal.get());}}
运行结果:
分析原因
那么, 究竟是什么原因导致的子线程无法访问父线程中的ThreadLocal变量呢,接下来研究ThreadLocal这个类的源码。
先看一下这个ThreadLocal类上的文档注释,大概了解ThreadLocal是用来干什么的
/*** This class provides thread-local variables. These variables differ from* their normal counterparts in that each thread that accesses one (via its* {@code get} or {@code set} method) has its own, independently initialized* copy of the variable. {@code ThreadLocal} instances are typically private* static fields in classes that wish to associate state with a thread (e.g.,* a user ID or Transaction ID).** <p>For example, the class below generates unique identifiers local to each* thread.* A thread's id is assigned the first time it invokes {@code ThreadId.get()}* and remains unchanged on subsequent calls.* <pre>* import java.util.concurrent.atomic.AtomicInteger;** public class ThreadId {* // Atomic integer containing the next thread ID to be assigned* private static final AtomicInteger nextId = new AtomicInteger(0);** // Thread local variable containing each thread's ID* private static final ThreadLocal<Integer> threadId =* new ThreadLocal<Integer>() {* @Override protected Integer initialValue() {* return nextId.getAndIncrement();* }* };** // Returns the current thread's unique ID, assigning it if necessary* public static int get() {* return threadId.get();* }* }* </pre>* <p>Each thread holds an implicit reference to its copy of a thread-local* variable as long as the thread is alive and the {@code ThreadLocal}* instance is accessible; after a thread goes away, all of its copies of* thread-local instances are subject to garbage collection (unless other* references to these copies exist).** @author Josh Bloch and Doug Lea* @since 1.2*/
关键注释
博主在类的文档注释上提取了几个关于ThreadLocal的重要的说明
This class provides thread-local variables.
这个类提供了线程本地变量
ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
ThreadLocal实例提供了可以关联一个线程的静态字段。
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
只要线程是存活状态,并且ThreadLocal对象可以访问,每个线程都拥有一个线程本地变量的副本的引用;
在线程执行完方法之后,所有线程本地变量都会被gc(垃圾收集器)回收,除非有其他变量引用了它。