InheritableThreadLocal

当在变量中维护的每线程属性(例如,用户 ID、事务 ID)必须自动传输到任何创建的子线程时,可优先使用可继承的线程局部变量而不是普通的线程局部变量。
测试代码

 private static ThreadLocal tl = new ThreadLocal<>();
    private static ThreadLocal tlInherit = new InheritableThreadLocal<>();

    public static void main(String[] args) throws Exception {
        log.info("1threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
        tl.set(Record.builder().id(3333L).build());
        tlInherit.set(Record.builder().id(3333L).build());
        log.info("2threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
        new Thread(() -> {
            Record record2 = Optional.ofNullable((Record)tl.get()).orElse(new Record());
            Record record2Inherit = Optional.ofNullable((Record)tlInherit.get()).orElse(new Record());
            record2.setId(2222L);
            record2Inherit.setId(2222L);
            log.info("3threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
        }).start();

        //保证下面fc执行一定在上面异步代码之后执行
        Thread.sleep(500);
        log.info("4threadName:{},tl = {}, tlInherit = {}", Thread.currentThread().getName(), tl.get(), tlInherit.get());
    }

运行结果
在这里插入图片描述
InheritableThreadLocal继承了ThreadLocal,重写了三个方法(childValue、getMap、createMap)。

源码:
在这里插入图片描述

childValue

当创建子线程时,子线程继承了父线程的局部变量。 通常情况下父子线程的值相同,可以通过childValue方法,可以将子项的值设为父项。

getMap

createMap

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值