阿里 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() = 工艺

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,线程变量传递是一件比较复杂的事情,因为线程是相互独立的,每个线程都有自己的栈空变量存储空。在多线程编程中,我们经常需要在线程传递某些变量或者数据,这就需要使用一些特殊的技术来实现。 其中一种技术就是使用 TransmittableThreadLocal(TTL)类,它可以让我们在多个线程传递变量,而且还可以保证变量的值在每个线程中都是唯一的。 TTL 是一个线程局部变量的扩展,它可以让我们在一个线程中创建一个变量,并且在任何一个子线程中都能够访问到这个变量的值。而且,当子线程结束时,TTL 会自动回收这个变量。 下面是一个使用 TTL 的示例代码: ``` import com.alibaba.ttl.TransmittableThreadLocal; public class Demo { private static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>(); public static void main(String[] args) { // 在主线程中设置值 threadLocal.set("value set in main thread"); // 创建子线程并启动 Thread thread = new Thread(() -> { // 在子线程中获取值 String value = threadLocal.get(); System.out.println("value in sub thread: " + value); }); thread.start(); } } ``` 在这个示例代码中,我们首先创建了一个 TTL 对象 threadLocal,然后在主线程中设置了一个值,接着创建了一个子线程,并在子线程中获取了这个值。当子线程结束时,TTL 会自动回收这个变量。 TTL 的原理比较简单,它使用了 Java 中的 InheritableThreadLocal 类来实现。当我们在主线程中创建了一个 TTL 变量时,它会将这个变量存储到 InheritableThreadLocal 中。当我们创建子线程时,子线程会继承主线程的 InheritableThreadLocal 对象,并且会在自己的线程中创建一个新的 TTL 变量,这个变量的值会从主线程中的变量中拷贝过来。当子线程结束时,TTL 会自动回收这个变量。 总的来说,TTL 是一个非常方便的工具,它可以让我们在多个线程传递变量,而且还能够保证变量的值在每个线程中都是唯一的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值