ThreadLocal、InheritableThreadLocal、transmittablethreadlocal简单记录

ThreadLocal

ThreadLocal用于保存线程线程本地变量,访问这个变量的每个线程都会有这个变量的一个本地副本,多个线程同时对这个变量进行读写操时,实际上操作的是线程自己本地内存中的变量,从而避免了线程安全的问题。

比如多个方法都用到某个参数,为了避免一直传递,可以放到ThreadLocal中。

//    threadLocal :主线程的threadLocal不会往子线程复制的,只是保留了一个空副本
    public static  final ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<>();
    static {
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("cnt",0);
        threadLocal.set(map);
    }
    public static void main(String[] args) {
        System.out.println(threadLocal.get().get("cnt"));
        CountDownLatch countDownLatch = new CountDownLatch(9);
        for (int i = 1;i<10;i++){
            int finalI = i;
            try {
                new Thread(new Runnable() {
                    public void run() {
                        //threadLocal 线程隔离这里会报空指针异常,所以一般我们都会做一个get方法,如果是空则付一下默认值
                        System.out.println(threadLocal.get().get("cnt"));
                    }
                }).start();

            }catch   (Exception e) {
                throw new RuntimeException("111");
            } finally {
                countDownLatch.countDown();
            }
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成,才会走下面的;
        } catch (Exception e) {
            throw new RuntimeException();
        }

    }

InheritableThreadLocal

能够使让子线程访问到父线程中设置的本地变量的值

//    InheritableThreadLocal 可以向子线程传递,这个复制是引用复制,即子线程的修改会反馈到主线程
    public static  final InheritableThreadLocal<Map<String,Object>> threadLocal = new InheritableThreadLocal<>();
    static {
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("cnt",0);
        threadLocal.set(map);
    }
    public static void main(String[] args) throws InterruptedException {
        System.out.println("最初:"+threadLocal.get().get("cnt"));
        CountDownLatch countDownLatch = new CountDownLatch(9);
        for (int i = 1;i<10;i++){
            int finalI = i;
                if (i==7){
                    Thread.sleep(i*100);
                }
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            Map<String, Object> subMap = threadLocal.get();
                            System.out.println(Thread.currentThread().getName()+"加之前:"+threadLocal.get().get("cnt"));
                            subMap.put("cnt",Integer.parseInt(subMap.get("cnt").toString())+finalI);
                            threadLocal.set(subMap);
                            System.out.println(Thread.currentThread().getName()+"加之后:"+threadLocal.get().get("cnt"));
                        }catch   (Exception e) {
                            throw new RuntimeException("111");
                        } finally {
                            countDownLatch.countDown();
                        }
                    }
                }).start();

        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成,才会走下面的;
        } catch (Exception e) {
            throw new RuntimeException();
        }
        System.out.println("最终:"+threadLocal.get().get("cnt"));
    }

InheritableThreadLocal可以保证子线程获得主线程的变量,其实是在线程创建的时候从主线程中对线程变量做了一个地址引用,所以说在子线程结束之后,主线程的线程变量也改变了。

这里需要考虑下,如果使用得当线程池,核心线程创建之后是不会销毁的,所以此变量就一直保留了下来。

阿里的transmittablethreadlocal  可以解决InheritableThreadLocal 和线程池搭配,核心线程不销毁,导致的InheritableThreadLocal 错乱问题。

TransmittableThreadLocal详解_邋遢的流浪剑客的博客-CSDN博客_transmittable-thread-local这个老哥写的挺详细的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值