1 概念
在Java
多线程编程中,通过ThreadLocal
实现了线程本地变量机制,通过空间换时间达到了线程隔离的目的。
但是,现在有这样一个需求:父线程中的线程本地变量需要传递给子线程使用。
针对这种情况,通过ThreadLocal
是无法完成的,因为ThreadLocal
中保存的是线程的本地变量,父线程的线程本地变量只有自己能拿到,子线程无法拿到。如下代码演示:
package com.tao.springbootdemo.thread;
public class ParentAndChildThreadMain {
public static void main(String[] args) {
// 父线程
Thread parentThread = new Thread(new Runnable() {
// 父线程中的线程局部变量
private ThreadLocal<String> threadLocal = new ThreadLocal<>();
// private InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
@Override
public void run() {
System.out.println("> 父线程中设置线程的本地变量");
threadLocal.set("local variable");
System.out.println("> 父线程中拿到的线程本地变量是:" + threadLocal.get());
// 在父线程中再起一个子线程
Thread childThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("> 子线程中获取父线程的本地变量");
System.out.println("> 子线程中拿到的父线程本地变量是:" + threadLocal.get());
}
});
childThread.setName("子线程!");
childThread.start();
}
});
parentThread.setName("父线程!");
parentThread.start();
}
}
得到的输出结果是:
> 父线程中设置线程的本地变量
> 父线程中拿到的线程本地变量是:local variable
> 子线程中获取父线程的本地变量
> 子线程中拿到的父线程本地变量是:null
Process finished with exit code 0
那么,怎样解决这个需求呢?
Java
提供了一个InheritableThreadLocal
来解决线程本地变量在父子线程中传递的问题!!!
如下代码演示:
package com.tao.springbootdemo.thread;
public class ParentAndChildThreadMain {
public static void main(String[] args) {
// 父线程
Thread parentThread = new Thread(new Runnable() {
// 父线程中的线程局部变量
// private ThreadLocal<String> threadLocal = new ThreadLocal<>();
private InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal