线程局部变量InheritableThreadLocal的使用
本文举例内容来自deepseek&copilot
1.InheritableThreadLocal 是 Java 中 ThreadLocal 的一个子类,它允许子线程继承父线程的线程局部变量值
InheritableThreadLocal 常用于以下场景:
-
传递上下文信息(如用户会话、跟踪ID等)到子线程
-
分布式跟踪系统中的上下文传递
-
需要在线程间传递特定信息的框架中
public class InheritableThreadLocalDemo {
//Create an inheritable thread local variable
private static final ThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {
// Set a value in the main thread
inheritableThreadLocal.set("BabaMama");
System.out.println("Value in main thread: " + inheritableThreadLocal.get());
// Create a child thread
Thread childThread = new Thread(() -> {
// Child threads can extend the values set by the parent thread
System.out.println("Value in child thread: " + inheritableThreadLocal.get());
//Modifying values in child threads will not affect the parent thread
inheritableThreadLocal.set("Baby");
System.out.println("Value in child thread: " + inheritableThreadLocal.get());
});
// Start the child thread
childThread.start();
try {
System.out.println("----------start-----------");
// Wait for the child thread to finish
childThread.join();
System.out.println("----------end-------------");
} catch (InterruptedException e) {
e.printStackTrace();
}
//The value of the main thread is not affected by the child threads
System.out.println("The final Value in main thread after child thread: " + inheritableThreadLocal.get());
// Clear the value in the main thread
inheritableThreadLocal.remove();
}
}
> Task :InheritableThreadLocalDemo.main()
Value in main thread: BabaMama
----------start-----------
Value in child thread: BabaMama
Value in child thread: Baby
----------end-------------
The final Value in main thread after child thread: BabaMama
2.线程池中的使用
public class ThreadPoolInheritableDemo {
// Create an inheritable thread local variable
private static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {
// Set a value in the main thread
inheritableThreadLocal.set("BabaMama");
System.out.println("Value in main thread: " + inheritableThreadLocal.get());
// Create a thread pool
ExecutorService executorService = Executors.newFixedThreadPool(2);
// task1 - Initialize the inheritable thread local variable in the main thread
Runnable task1 = () -> {
inheritableThreadLocal.set("task1-Initialize");
System.out.println("task1: " + inheritableThreadLocal.get());
};
// task2 - try to get value
Runnable task2 = () -> {
System.out.println("task2: " + inheritableThreadLocal.get());
};
// Submit task to the thread pool
executorService.submit(task1);
executorService.submit(task2);
// Shutdown the executor service,Waiting for task completion
executorService.shutdown();
try {
System.out.println("----------start-----------");
// Wait for all tasks to finish
if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
executorService.shutdownNow();
}
System.out.println("----------end-------------");
} catch (InterruptedException e) {
e.printStackTrace();
}
// The value of the main thread is not affected by the child threads
System.out.println("The final Value in main thread after child thread: " + inheritableThreadLocal.get());
// Clear the value in the main thread
inheritableThreadLocal.remove();
}
}
第一次运行可能的结果:
> Task :ThreadPoolInheritableDemo.main()
Value in main thread: BabaMama
----------start-----------
task1: task1-Initialize
task2: BabaMama
----------end-------------
The final Value in main thread after child thread: BabaMama
再次运行,可能的结果如下:
> Task :ThreadPoolInheritableDemo.main()
Value in main thread: BabaMama
----------start-----------
task2: BabaMama
task1: task1-Initialize
----------end-------------
The final Value in main thread after child thread: BabaMama
注意事项
-
在线程池中使用时要小心,因为线程是复用的,可能导致数据混乱
-
子线程修改值不会影响父线程的值
-
可能会引起内存泄漏,使用后应及时清理(调用 remove() 方法)

浙公网安备 33010602011771号