使用TransmittableThreadLocal弥补InheritableThreadLocal的不足,可动态刷新线程变量

本文通过实例对比了InheritableThreadLocal与TransmittableThreadLocal在线程池中的表现,展示了如何使用TransmittableThreadLocal解决线程间数据同步问题。

众所周知,使用InheritableThreadLocal可以实现父子线程之间的值传递,不过使用InheritableThreadLocal有一个隐藏的问题,子线程在创建的时候会从父线程InheritableThreadLocal中拷贝数据,一旦子线程创建成功以后,父线程更新了数据,对子线程是无效的,这种情况在使用线程池的时候会有数据不安全的问题,下面使用代码演示一下:

public class ITLTest {
   
   
    // 声明一个线程池
    private static final ExecutorService pool = Executors.newFixedThreadPool(2);
    // 声明一个InheritableThreadLocal全局变量
    private static final ThreadLocal<String> tl = new InheritableThreadLocal<>();

    public static void main(String[] args) {
   
   
        // 设置一个值
        tl.set("张三");

        System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
        // 声明一个Runnable对象
        Runnable r1 = () -> {
   
   
            System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
        };
        // 向线程池提交
        pool.submit(r1);
        // 声明一个Callable对象
        Callable<String> c1 = () -> {
   
   
            System.out.println(Thread.currentThread().getName() + "--->" + tl.get());
            return "success";
        };
        // 向线程池提交
        pool.submit(c1);

        tl.set("李四"); // 更新tl中的值
        try {
   
   
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
   
   
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "--->" + tl.get
TransmittableThreadLocalInheritableThreadLocal都是用于解决线程间上下文传递的问题,但是它们的实现方式略有不同。 TransmittableThreadLocal是可传输的线程局部变量,它可以在使用线程池等会池化复用线程的执行组件情况下,提供ThreadLocal值的传递功能。也就是说,当一个线程线程池中取出来执行任务时,它可以获取到之前设置的TransmittableThreadLocal的值,从而保证了上下文的传递。TransmittableThreadLocal继承自InheritableThreadLocal。 而InheritableThreadLocal是可继承的线程局部变量,它用于父线程传递本地变量到子线程。当一个线程创建子线程时,子线程可以获取到父线程设置的InheritableThreadLocal的值,从而保证了上下文的传递。InheritableThreadLocal继承自ThreadLocal,并且重写了父类的方法:childValue、getMap、createMap。 因此,TransmittableThreadLocalInheritableThreadLocal的区别在于它们的应用场景和实现方式不同。 代码演示如下: ```python import threading from threading import Thread, current_thread from concurrent.futures import ThreadPoolExecutor from threading import Lock from concurrent.futures import Future from threading import Event from threading import Semaphore from threading import Barrier from threading import Condition from threading import Timer from threading import ThreadLocal, local from concurrent.futures import as_completed from concurrent.futures import wait from concurrent.futures import FIRST_COMPLETED from concurrent.futures import ALL_COMPLETED from collections import deque from threading import InheritableThreadLocal, current_thread from threading import Thread # InheritableThreadLocal class MyLocal(InheritableThreadLocal): def __init__(self, value): self.value = value def __repr__(self): return str(self.value) local_data = MyLocal(1) def worker(): print(current_thread().getName(), 'starts with', local_data) local_data.value += 1 print(current_thread().getName(), 'ends with', local_data) t = Thread(target=worker) t.start() t.join() # TransmittableThreadLocal from pytransmit import TransmitThreadLocal transmit_data = TransmitThreadLocal() def worker(): print(current_thread().getName(), 'starts with', transmit_data.get()) transmit_data.set(2) print(current_thread().getName(), 'ends with', transmit_data.get()) t = Thread(target=worker) t.start() t.join() ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder-文小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值