多线程 - 父线程向子线程传值方案探讨

2023-10-14 13:32

本文主要是介绍多线程 - 父线程向子线程传值方案探讨,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 . ThreadLocal

测试代码:

public class TestThreadLocal {public static ThreadLocal<String> threadLocal = new ThreadLocal<>();public static void main(String[] args) {//设置线程变量threadLocal.set("hello world");Thread thread = new Thread(new Runnable() {@Overridepublic void run( ) {//子线程输出线程变量的值System.out.println("thread:"+threadLocal.get());}});thread.start();// 主线程输出线程变量的值System.out.println("main:"+threadLocal.get());}
}

输出结果:

main:hello world
thread:null

从上面结果可以看出:同一个ThreadLocal变量在父线程中被设置后,在子线程中是获取不到的;

原因在子线程thread里面调用get方法时当前线程为thread线程,而这里调用set方法设置线程变量的是main线程,两者是不同的线程,自然子线程访问时返回null

为了解决上面的问题,InheritableThreadLocal应运而生,InheritableThreadLocal继承ThreadLocal,其提供一个特性,就是让子线程可以访问在父线程中设置的本地变量,我们上面代码修改为

2. InheritableThreadLocal

测试代码

将上面测试代码用InheritableThreadLocal修改

public class TestInheritableThreadLocal {public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();public static void main(String[] args) {//设置线程变量threadLocal.set("hello world");Thread thread = new Thread(new Runnable() {@Overridepublic void run( ) {//子线程输出线程变量的值System.out.println("thread:"+threadLocal.get());}});thread.start();// 主线程输出线程变量的值System.out.println("main:"+threadLocal.get());}
}

输出结果:

main:hello world
thread:hello world

源码分析:

public class InheritableThreadLocal<T> extends ThreadLocal<T> {protected T childValue(T parentValue) {return parentValue;}ThreadLocalMap getMap(Thread t) {return t.inheritableThreadLocals;}void createMap(Thread t, T firstValue) {t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);}
}

InheritableThreadLocal 重写了childValue,getMap,createMap三个方法
在InheritableThreadLocal中,变量inheritableThreadLocals 替代了threadLocals;

那么如何让子线程可以访问父线程的本地变量。这要从创建Thread的代码说起,打开Thread类的默认构造方法,代码如下:

  public Thread(Runnable target) {init(null, target, "Thread-" + nextThreadNum(), 0);}private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,boolean inheritThreadLocals) {if (name == null) {throw new NullPointerException("name cannot be null");}this.name = name;//获取当前线程Thread parent = currentThread();//如果父线程的 inheritableThreadLocals变量不为nullif (inheritThreadLocals && parent.inheritableThreadLocals != null)//设置子线程inheritThreadLocals变量this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);/* Stash the specified stack size in case the VM cares */this.stackSize = stackSize;/* Set thread ID */tid = nextThreadID();}

我们看下createInheritedMap代码:

this.inheritableThreadLocals =            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

在createInheritedMap内部使用父线程的inheritableThreadLocals变量作为构造方法创建了一个新的ThreadLocalMap变量,然后赋值给子线程的inheritableThreadLocals变量。下面看看ThreadLocalMap的构造函数内部做了什么事情;

private ThreadLocalMap(ThreadLocalMap parentMap) {Entry[] parentTable = parentMap.table;int len = parentTable.length;setThreshold(len);table = new Entry[len];for (int j = 0; j < len; j++) {Entry e = parentTable[j];if (e != null) {@SuppressWarnings("unchecked")ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();if (key != null) {Object value = key.childValue(e.value);Entry c = new Entry(key, value);int h = key.threadLocalHashCode & (len - 1);while (table[h] != null)h = nextIndex(h, len);table[h] = c;size++;}}}}

InheritableThreadLocal 类通过重写下面代码

 ThreadLocalMap getMap(Thread t) {return t.inheritableThreadLocals;}/*** Create the map associated with a ThreadLocal.** @param t the current thread* @param firstValue value for the initial entry of the table.*/void createMap(Thread t, T firstValue) {t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);}

让本地变量保存到了具体的线程的inheritableThreadLocals变量里面,那么线程在通过InheritableThreadLocal类实例的set或者get方法设置变量时,就会创建当前线程的inheritableThreadLocals变量。

当父线程创建子线程时,构造方法会把父线程中的inheritableThreadLocals变量里面的本地变量赋值一份保存到子线程的inheritableThreadLocals变量里面

InheritableThreadLocal存在的问题

虽然InheritableThreadLocal可以解决在子线程中获取父线程的值的问题,但是在使用线程池的情况下,由于不同的任务有可能是同一个线程处理,因此这些任务取到的值有可能并不是父线程设置的值
测试目标:任务1和任务2 获取父线程值一样,为测试代码中的hello world
测试代码:

public class TestInheritableThreadLocaIssue {public static InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();public static ExecutorService executorService = Executors.newSingleThreadExecutor();public static void main(String[] args) throws Exception {//设置线程变量threadLocal.set("hello world");Thread thread1 = new Thread(new Runnable() {@Overridepublic void run( ) {//子线程输出线程变量的值System.out.println("thread:"+threadLocal.get());threadLocal.set("hello world 2");}},"task1");Thread thread2 = new Thread(new Runnable() {@Overridepublic void run( ) {//子线程输出线程变量的值System.out.println("thread:"+threadLocal.get());threadLocal.set("hello world 2");}},"task2");executorService.submit(thread1).get();executorService.submit(thread2).get();// 主线程输出线程变量的值System.out.println("main:"+threadLocal.get());}
}

输出结果:

thread:hello world
thread:hello world 2
main:hello world

结果分析:
很明显,任务2获取的不是父线程设置的hello world ,而是线程1修改后的值。如果在线程池中使用,需要注意这种情况(可以备份备份父线程的值)

3. TransmittableThreadLocal(解决线程池化值传递)

阿里封装了一个工具,实现了在使用线程池等会池化复用线程的组件情况下,提供ThreadLocal值的传递功能,解决异步执行时上下文传递的问题

JDK的InheritableThreadLocal类可以完成父线程到子线程的值传递。但对于使用线程池等会池化复用线程的执行组件的情况,线程由线程池创建好,并且线程是池化起来反复使用的;这时父子线程关系的ThreadLocal值传递已经没有意义,应用需要的实际上是把 任务提交给线程池时的ThreadLocal值传递到 任务执行时
[https://github.com/alibaba/transmittable-thread-local]
引入:

<dependency><groupId>com.alibaba</groupId><artifactId>transmittable-thread-local</artifactId><version>2.11.5</version>
</dependency>

需求场景:
1.分布式跟踪系统 或 全链路压测(即链路打标)
2.日志收集记录系统上下文
3.Session级Cache
4.应用容器或上层框架跨应用代码给下层SDK传递信息

测试代码:
1)父子线程信息传递

public static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();public static void main(String[] args) {//设置线程变量threadLocal.set("hello world");Thread thread = new Thread(new Runnable() {@Overridepublic void run( ) {//子线程输出线程变量的值System.out.println("thread:"+threadLocal.get());}});thread.start();// 主线程输出线程变量的值System.out.println("main:"+threadLocal.get());}
}

输出结果:

main:hello world
thread:hello world

2)线程池中传递值,参考github
修饰线程池

这篇关于多线程 - 父线程向子线程传值方案探讨的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/210842

相关文章

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

Vue中组件之间传值的六种方式(完整版)

《Vue中组件之间传值的六种方式(完整版)》组件是vue.js最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用,针对不同的使用场景,如何选择行之有效的通信方式... 目录前言方法一、props/$emit1.父组件向子组件传值2.子组件向父组件传值(通过事件形式)方

IDEA中Git版本回退的两种实现方案

《IDEA中Git版本回退的两种实现方案》作为开发者,代码版本回退是日常高频操作,IntelliJIDEA集成了强大的Git工具链,但面对reset和revert两种核心回退方案,许多开发者仍存在选择... 目录一、版本回退前置知识二、Reset方案:整体改写历史1、IDEA图形化操作(推荐)1.1、查看提

Python实现html转png的完美方案介绍

《Python实现html转png的完美方案介绍》这篇文章主要为大家详细介绍了如何使用Python实现html转png功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 1.增强稳定性与错误处理建议使用三层异常捕获结构:try: with sync_playwright(

Java使用多线程处理未知任务数的方案介绍

《Java使用多线程处理未知任务数的方案介绍》这篇文章主要为大家详细介绍了Java如何使用多线程实现处理未知任务数,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 知道任务个数,你可以定义好线程数规则,生成线程数去跑代码说明:1.虚拟线程池:使用 Executors.newVir

Java终止正在运行的线程的三种方法

《Java终止正在运行的线程的三种方法》停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作,停止一个线程可以用Thread.stop()方法,但最好不要用它,本文给大家介绍了... 目录前言1. 停止不了的线程2. 判断线程是否停止状态3. 能停止的线程–异常法4. 在沉睡中停止5

MySQL中闪回功能的方案讨论及实现

《MySQL中闪回功能的方案讨论及实现》Oracle有一个闪回(flashback)功能,能够用户恢复误操作的数据,这篇文章主要来和大家讨论一下MySQL中支持闪回功能的方案,有需要的可以了解下... 目录1、 闪回的目标2、 无米无炊一3、 无米无炊二4、 演示5、小结oracle有一个闪回(flashb