ThreadLocal父子间通信的四种解决方案
ThreadLocal父子间通信的四种解决方案
ThreadLocal 是存储在线程栈帧中的一块数据存储区域,其可以做到线程与线程之间的读写隔离。
但是在我们的日常场景中,经常会出现父线程需要向子线程中传递消息,而 ThreadLocal 仅能在当前线程上进行数据缓存,这里就介绍4种父子间通信问题;
- 在子线程中手动设置父线程的值
- ThreadPoolTaskExecutor + TaskDecorator
- InheritableThreadLocal
- TransmittableThreadLocal
1.在子线程中手动设置父线程的值
ThreadLocal<String> threadLocal = new ThreadLocal<>();
@BeforeEach
public void init() {
threadLocal.set("thread-01");
}
@Test
public void test4() {
String s = threadLocal.get();
new Thread(() -> {
threadLocal.set(s);
System.out.println(threadLocal.get());
}).start();
threadLocal.remove();
}
在子线程里手动的设置变量,@BeforeEach是junit5的写法,对应junit4的Before
输出结果: thread-01
2.ThreadPoolTaskExecutor + TaskDecorator
使用ThreadPoolTaskExecutor线程池的时候,可自定义一个TaskDecorator包装类,这个类的作用就是在执行子线程之前手动的设置父线程的变量,跟第一种方法类似;
- 储存线程用户信息
public class UserContextUtils {
private static final ThreadLocal<String> userThreadLocal = new ThreadLocal<>();
public static void set(String username) {
userThreadLocal.set(username);
}
public static String get() {
return userThreadLocal.get();
}
public static void clear() {
userThreadLocal.remove();
}
}
- 这是一个执行回调方法的装饰器,主要应用于传递上下文,或者提供任务的监控/统计信息
public class ContextTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
String username = UserContextUtils.get();
return () -> {
try {
// 将主线程的请求信息,设置到子线程中
UserContextUtils.set(username);
// 执行子线程,这一步不要忘了
runnable.run();
} finally {
// 线程结束,清空这些信息,否则可能造成内存泄漏
UserContextUtils.clear();
}
};
}
}
- 初始化线程池
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(100);
executor.setAllowCoreThreadTimeOut(false);
executor.setKeepAliveSeconds(0);
executor.setThreadNamePrefix("DefaultAsync-");
executor.setTaskDecorator(new ContextTaskDecorator());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
System.out.println("初始化Async的线程池");
return executor;
}
- 测试
@BeforeEach
public void init() {
threadLocal.set("thread-01");
UserContextUtils.set("taskExecutor");
}
@Resource
private ThreadPoolTaskExecutor getAsyncExecutor;
@Test
public void test3() {
getAsyncExecutor.execute(()->{
System.out.println(UserContextUtils.get());
});
}
使用ThreadPoolTaskExecutor线程池的时候,使用构造器在子线程写入主线程参数,但是使用ThreadPoolExecutor就不能这么做了,建议使用第四种方式TTL;
3.InheritableThreadLocal
inheritableThreadLocal是ThreadLocal中自带的一种方法,只要替换原来的ThreadLocal就行了,但是这种方法有缺陷,会存在核心线程旧值的重复使用,不建议使用;
这里我设置一个线程池,核心线程数为2个,核心线程数重复使用的时候不会重新拿新值,而是用原来的旧值
@Test
public void test1() {
//1.创建一个自己定义的线程池
ExecutorService executorService = new ThreadPoolExecutor(2, 3, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
threadLocal.set("thread-01");
executorService.execute(() -> {
String s = threadLocal.get();
System.out.println(s);
});
threadLocal.set("thread-02");
executorService.execute(() -> {
String s = threadLocal.get();
System.out.println(s);
});
threadLocal.set("thread-03");
executorService.execute(() -> {
String s = threadLocal.get();
System.out.println(s);
});
threadLocal.set("thread-04");
executorService.execute(() -> {
String s = threadLocal.get();
System.out.println(s);
});
}
测试结果: 因为线程2被重复使用
thread-01
thread-02
thread-02
thread-02
4.TransmittableThreadLocal
TransmittableThreadLocal 是Alibaba开源的、用于解决 “在使用线程池等会缓存线程的组件情况下传递ThreadLocal” 问题的 InheritableThreadLocal 扩展。若希望 TransmittableThreadLocal 在线程池与主线程间传递,需配合 TtlExecutors.getTtlExecutorService,TtlRunnable 和 TtlCallable 使用。
- 引入TTL的jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.12.6</version>
</dependency>
- TtlExecutors.getTtlExecutorService()
使用Ttl提供的TtlExecutors.getTtlExecutorService来对原来线程池进行包装,但是此时变量需要使用TransmittableThreadLocal,建议使用这种方式;
@Test
public void test2() {
// 1. 创建一个自己定义的线程池
ExecutorService executorService = new ThreadPoolExecutor(2, 3, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
// 2. 使用TransmittableThreadLocal修饰变量
TransmittableThreadLocal<String> threadLocal1 = new TransmittableThreadLocal<>();
// 3. 使用TtlExecutors.getTtlExecutorService包装线程池
ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);
threadLocal1.set("thread-01");
ttlExecutorService.execute(() -> {
String s = threadLocal1.get();
System.out.println(s);
});
threadLocal1.set("thread-02");
ttlExecutorService.execute(() -> {
String s = threadLocal1.get();
System.out.println(s);
});
threadLocal1.set("thread-03");
ttlExecutorService.execute(() -> {
String s = threadLocal1.get();
System.out.println(s);
});
threadLocal1.set("thread-04");
ttlExecutorService.execute(() -> {
String s = threadLocal1.get();
System.out.println(s);
});
}
thread-01
thread-02
thread-03
thread-04
- TtlRunnable.get()
@Test
public void test5() {
// 1. 创建一个自己定义的线程池
ExecutorService executorService = new ThreadPoolExecutor(2, 3, 2, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
// 2. 使用TransmittableThreadLocal修饰变量
TransmittableThreadLocal<String> threadLocal1 = new TransmittableThreadLocal<>();
threadLocal1.set("thread-01");
executorService.execute(TtlRunnable.get(() -> {
String s = threadLocal1.get();
System.out.println(s);
}));
threadLocal1.set("thread-02");
executorService.execute(TtlRunnable.get(() -> {
String s = threadLocal1.get();
System.out.println(s);
}));
threadLocal1.set("thread-03");
executorService.execute(TtlRunnable.get(() -> {
String s = threadLocal1.get();
System.out.println(s);
}));
threadLocal1.set("thread-04");
executorService.execute(TtlRunnable.get(() -> {
String s = threadLocal1.get();
System.out.println(s);
}));
}
thread-01
thread-02
thread-03
thread-04
ThreadLocal父子间通信的四种解决方案的更多相关文章
- vue-learning:31 - component - 组件间通信的6种方法
vue组件间通信的6种方法 父子组件通信 prop / $emit 嵌套组件 $attrs / $liteners 后代组件通信 provide / inject 组件实例引用 $root / $pa ...
- Mybatis多参传递的四种解决方案
Mybatis多参传递的四种解决方案 代码异常:org.apache.ibatis.binding.BindingException: Parameter 'param' not found. 长时间 ...
- ios页面间传递参数四种方式
ios页面间传递参数四种方式 1.使用SharedApplication,定义一个变量来传递. 2.使用文件,或者NSUserdefault来传递 3.通过一个单例的class来传递 4.通过Dele ...
- iOS多线程全套:线程生命周期,多线程的四种解决方案,线程安全问题,GCD的使用,NSOperation的使用
目的 本文主要是分享iOS多线程的相关内容,为了更系统的讲解,将分为以下7个方面来展开描述. 多线程的基本概念 线程的状态与生命周期 多线程的四种解决方案:pthread,NSThread,GCD,N ...
- 直接将字典转为DataFrame格式时,会出现:ValueError: If using all scalar values, you must pass an index(四种解决方案)
问题:想要将字典直接转为DataFrame格式时,除了字典外没有传入其他参数时,会报错 ValueError: If using all scalar values, you must pass an ...
- vue组件父子间通信之综合练习--假的聊天室
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- 父子间通信四 ($dispatch 和 $broadcast用法)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- [转] 微信小程序页面间通信的5种方式
微信小程序页面间通的5种方式 PageModel(页面模型)对小程序而言是很重要的一个概念,从app.json中也可以看到,小程序就是由一个个页面组成的. 如上图,这是一个常见结构的小程序:首页是一个 ...
- VC 线程间通信的三种方式
1.使用全局变量(窗体不适用) 实现线程间通信的方法有很多,常用的主要是通过全局变量.自定义消息和事件对象等来实现的.其中又以对全局变量的使用最为简洁.该方法将全局变量作为线程监视的对象,并通 ...
- 【转】VC 线程间通信的三种方式
原文网址:http://my.oschina.net/laopiao/blog/94728 1.使用全局变量(窗体不适用) 实现线程间通信的方法有很多,常用的主要是通过全局变量.自定义消息和 ...
随机推荐
- go中bufio使用小结
bufio 前言 例子 bufio 源码解析 Reader对象 实例化 ReadSlice ReadString ReadLine Peek Scanner Give me more data Err ...
- 【1】paddle飞桨框架高层API使用讲解
1.高层API简介 飞桨框架2.0全新推出高层API,是对飞桨API的进一步封装与升级,提供了更加简洁易用的API,进一步提升了飞桨的易学易用性,并增强飞桨的功能. 飞桨高层API由五个模块组成:数据 ...
- 阿里云数仓Dataworks数据导出到文件step by step
背景 假设你在阿里云上Dataworks的空间space下有一个表table_A,想要把它的数据导出到文件以供后续使用,但是数据量又很多,从浏览器复制不太现实.阿里云提供了Java和Python版本的 ...
- 优化利器In-Memory开启和效果
本文主要介绍Oracle In-Memory 选件,Oracle在12.1.0.2就已经推出了In-Memory这个选件,现在通常会建议所有使用19.8及之后版本的用户,有条件都要留给In-memor ...
- 虚拟机 VMware Workstation 16 PRO 的网络配置
原文地址: https://blog.csdn.net/weixin_41905135/article/details/123858658 (一)VMware编辑虚拟网络 默认情况下,VMware ...
- [Java]《On Java》阅读记录之 -- 可变参数重载问题
<On Java>阅读记录之 -- 可变参数重载问题 有下面一段代码: public class OverloadingVarargs2 { static void f(float i , ...
- HASHTEAM香山杯2023WP
目录 前言 misc 签到题 web PHP_unserialize_pro Re URL从哪儿来 hello python pwn Move pwthon 附上c-python调试方法 crypto ...
- [技术选型与调研] 流程引擎/工作流引擎:Activiti、Flowable、Camunda
1 概述:流程与流程引擎 低代码平台.办公自动化(OA).BPM平台.工作流系统均需要流程引擎功能 [工作流引擎的三大功能] 1)验证当前过程状态:在给定当前状态的情况下,检查是否有效执行任务. 2) ...
- ELK查询和汇总
查询表明细: ELK的KQL样例,显示时间请选择最近15天: 样例1:查询ol_lc 表增删改查,不是jy2_rw的账号明细 KQL:(ol_lc or oc.ol_lc) and (select o ...
- 我的小程序之旅八:基于weixin-java-mp实现微信公众号被动回复消息
在微信里有这样一个公众号[华为运动健康],当点击最新排行的时候,公众号就会发送今天最新的运动步数给你.如下图: 这里有两种格式的消息 1.有头像框,有聊天框--普通消息 2.消息有样式.颜色等--模板 ...