本文主要是介绍阿里 TransmittableThreadLocal 解决 线程池模式下,线程间变量传递的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为什么用
因为jdk中的ThreadLocal,InheritableThreadLocal 无法在父子线程,父线程与线程池之间变量的传递
关键代码
private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();// 创建一个固定大小的线程池,实际中肯定不这样建,demo用下ExecutorService executorService = Executors.newFixedThreadPool(2);
// 使用TtlExecutors包装线程池,关键点ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);
1 pom.xml配置
<dependency><groupId>com.alibaba</groupId><artifactId>transmittable-thread-local</artifactId><version>2.14.2</version>
</dependency>
2 示例
package org.example.controller;import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;
import java.util.ArrayList;
import java.util.concurrent.*;public class TtlExecutorsDemo {private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建一个固定大小的线程池ExecutorService executorService = Executors.newFixedThreadPool(2);// 使用TtlExecutors包装线程池ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);// 在主线程中设置TransmittableThreadLocal的值threadLocal.set("工艺");// 提交任务到线程池中ArrayList<Future<String>> futures = new ArrayList<>();for (int i = 0; i <2 ; i++) {Future<String> future = ttlExecutorService.submit(() -> {TimeUnit.SECONDS.sleep(2); // 模拟耗时操作String value = threadLocal.get();System.out.println(Thread.currentThread().getName() + "---------" + value);return value;});futures.add(future);}futures.forEach(future ->{try {System.out.println("future.get() = " + future.get());} catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);}});// 关闭线程池ttlExecutorService.shutdown();while (!ttlExecutorService.awaitTermination(1, TimeUnit.SECONDS)) {// 等待直到所有任务完成}}
}
3 效果
pool-1-thread-1---------工艺
pool-1-thread-2---------工艺
future.get() = 工艺
future.get() = 工艺
这篇关于阿里 TransmittableThreadLocal 解决 线程池模式下,线程间变量传递的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!