当前位置:   article > 正文

阿里 TransmittableThreadLocal 解决 线程池模式下,线程间变量传递的问题_阿里 threadlocal 线程传递

阿里 threadlocal 线程传递

为什么用
因为jdk中的ThreadLocal,InheritableThreadLocal 无法在父子线程,父线程与线程池之间变量的传递

关键代码

  1. private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
  2. // 创建一个固定大小的线程池,实际中肯定不这样建,demo用下
  3. ExecutorService executorService = Executors.newFixedThreadPool(2);
  4. // 使用TtlExecutors包装线程池,关键点
  5. ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);


1 pom.xml配置

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>transmittable-thread-local</artifactId>
  4. <version>2.14.2</version>
  5. </dependency>

2 示例

  1. package org.example.controller;
  2. import com.alibaba.ttl.TransmittableThreadLocal;
  3. import com.alibaba.ttl.threadpool.TtlExecutors;
  4. import java.util.ArrayList;
  5. import java.util.concurrent.*;
  6. public class TtlExecutorsDemo {
  7. private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
  8. public static void main(String[] args) throws ExecutionException, InterruptedException {
  9. // 创建一个固定大小的线程池
  10. ExecutorService executorService = Executors.newFixedThreadPool(2);
  11. // 使用TtlExecutors包装线程池
  12. ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);
  13. // 在主线程中设置TransmittableThreadLocal的值
  14. threadLocal.set("工艺");
  15. // 提交任务到线程池中
  16. ArrayList<Future<String>> futures = new ArrayList<>();
  17. for (int i = 0; i <2 ; i++) {
  18. Future<String> future = ttlExecutorService.submit(() -> {
  19. TimeUnit.SECONDS.sleep(2); // 模拟耗时操作
  20. String value = threadLocal.get();
  21. System.out.println(Thread.currentThread().getName() + "---------" + value);
  22. return value;
  23. });
  24. futures.add(future);
  25. }
  26. futures.forEach(future ->{
  27. try {
  28. System.out.println("future.get() = " + future.get());
  29. } catch (InterruptedException e) {
  30. throw new RuntimeException(e);
  31. } catch (ExecutionException e) {
  32. throw new RuntimeException(e);
  33. }
  34. });
  35. // 关闭线程池
  36. ttlExecutorService.shutdown();
  37. while (!ttlExecutorService.awaitTermination(1, TimeUnit.SECONDS)) {
  38. // 等待直到所有任务完成
  39. }
  40. }
  41. }

3 效果

  1. pool-1-thread-1---------工艺
  2. pool-1-thread-2---------工艺
  3. future.get() = 工艺
  4. future.get() = 工艺

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/763608
推荐阅读
相关标签
  

闽ICP备14008679号