ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal 区别,使用场景 示例

总结:
ThreadLocal :set,get 需要再同一个线程中执行,父子线程不支持
InheritableThreadLocal :支持父子线程,不支持线程池
TransmittableThreadLocal :以上都支持

代码示例
1 pom.xml

复制代码
<!-- 阿里线程传递值 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.14.3</version>
        </dependency>

2 ThreadLocal,InheritableThreadLocal 对比

复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;

public class InheritableThreadLocalExample {

    static Logger logger = LoggerFactory.getLogger(InheritableThreadLocalExample.class);

    /**
     * 输出结果
     *  [main] [traceId:] - userName:张三
     *  [thread1] [traceId:] - userName:null
     * @throws InterruptedException
     */
    private static void threadLocalTest() throws InterruptedException {
        ThreadLocal<String> userNameTL = new ThreadLocal<>();

        //这里是主线程,ThreadLocal中设置了值:张三
        userNameTL.set("张三");
        logger.info("userName:{}", userNameTL.get());

        //创建了一个子线程thread1,在子线程中去ThreadLocal中拿值,能否拿到刚才放进去的"张三"呢?
        new Thread(() -> {
            logger.info("userName:{}", userNameTL.get());
        }, "thread1").start();

        TimeUnit.SECONDS.sleep(1);
    }

    /**
     * 输出结果
     *  [main] [traceId:] - userName:张三
     *  [thread1] [traceId:] - userName:张三
     *
     * @throws InterruptedException
     */
    private static void inheritableThreadLocal() throws InterruptedException {

        InheritableThreadLocal<String> userNameItl = new InheritableThreadLocal<>();

        //这里是主线程,使用 InheritableThreadLocal.set 放入值:张三
        userNameItl.set("张三");
        logger.info("userName:{}", userNameItl.get());

        //创建了一个子线程thread1,在子线程中去ThreadLocal中拿值,能否拿到刚才放进去的"张三"呢?
        new Thread(() -> {
            logger.info("userName:{}", userNameItl.get());
        }, "thread1").start();
        TimeUnit.SECONDS.sleep(1);
    }

    public static void main(String[] args) throws InterruptedException {
        threadLocalTest();

        System.out.println();

        inheritableThreadLocal();
    }
}

3 InheritableThreadLocal ,TransmittableThreadLocal 对比

复制代码
import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TransmittableThreadLocalExample {

    static Logger logger = LoggerFactory.getLogger(TransmittableThreadLocalExample.class);

    /**
     * 输出结果
     *  [main] [traceId:] - userName:张三
     *  [pool-1-thread-1] [traceId:] - 第1次获取 userName:张三
     *  [main] [traceId:] - userName:李四
     *  [pool-1-thread-1] [traceId:] - 第2次获取 userName:张三
     *
     * @throws InterruptedException
     */
    private static void fangfa_Inheri_test() throws InterruptedException {

        InheritableThreadLocal<String> userNameTtl = new InheritableThreadLocal<String>();

        // 为了看到效果,这里创建大小为1的线程池,注意这里为1才能方便看到效果
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        // 主线程中设置 张三
        userNameTtl.set("张三");
        logger.info("userName:{}", userNameTtl.get());

        // 在线程池中通过 TransmittableThreadLocal 拿值,看看能否拿到 刚才放入的张三?
        executorService.execute(() -> {
            logger.info("第1次获取 userName:{}", userNameTtl.get());
        });
        TimeUnit.SECONDS.sleep(1);

        // 这里放入了李四
        userNameTtl.set("李四");
        logger.info("userName:{}", userNameTtl.get());

        // 在线程池中通过 TransmittableThreadLocal 拿值,看看能否拿到 刚才放入的李四?
        executorService.execute(() -> {
            // 在线程池中通过 inheritableThreadLocal 拿值,看看能否拿到?
            logger.info("第2次获取 userName:{}", userNameTtl.get());
        });

        TimeUnit.SECONDS.sleep(1);
    }

    /**
     * 输出结果
     *  [main] [traceId:] - userName:张三
     *  [pool-1-thread-1] [traceId:] - 第1次获取 userName:张三
     *  [main] [traceId:] - userName:李四
     *  [pool-1-thread-1] [traceId:] - 第2次获取 userName:李四
     *
     * @throws InterruptedException
     */
    private static void fangfa_Transmit_test() throws InterruptedException {

        TransmittableThreadLocal<String> userNameTtl = new TransmittableThreadLocal<String>();

        // 为了看到效果,这里创建大小为1的线程池,注意这里为1才能方便看到效果
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        // 这里需要用 TtlExecutors.getTtlExecutorService 将原线程池包装下
        executorService = TtlExecutors.getTtlExecutorService(executorService);

        // 主线程中设置 张三
        userNameTtl.set("张三");
        logger.info("userName:{}", userNameTtl.get());

        // 在线程池中通过 TransmittableThreadLocal 拿值,看看能否拿到 刚才放入的张三?
        executorService.execute(() -> {
            logger.info("第1次获取 userName:{}", userNameTtl.get());
        });
        TimeUnit.SECONDS.sleep(1);

        // 这里放入了李四
        userNameTtl.set("李四");
        logger.info("userName:{}", userNameTtl.get());

        // 在线程池中通过 TransmittableThreadLocal 拿值,看看能否拿到 刚才放入的李四?
        executorService.execute(() -> {
            // 在线程池中通过 inheritableThreadLocal 拿值,看看能否拿到?
            logger.info("第2次获取 userName:{}", userNameTtl.get());
        });

        TimeUnit.SECONDS.sleep(1);
    }


    public static void main(String[] args) throws InterruptedException {
        fangfa_Inheri_test();

        System.out.println();

        fangfa_Transmit_test();
    }
}
相关推荐
llwszx2 小时前
深入理解Java锁原理(一):偏向锁的设计原理与性能优化
java·spring··偏向锁
云泽野3 小时前
【Java|集合类】list遍历的6种方式
java·python·list
二进制person3 小时前
Java SE--方法的使用
java·开发语言·算法
小阳拱白菜4 小时前
java异常学习
java
FrankYoou5 小时前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*6 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了6 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
天河归来6 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
weixin_478689767 小时前
十大排序算法汇总
java·算法·排序算法
码荼7 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud