赞
踩
为什么用
因为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() = 工艺
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。