zoukankan      html  css  js  c++  java
  • ThreadLocal

    将ThreadLocal设置为静态变量,在set或get值得时候,会通过Thread.currentThread()拿到当前操作线程,在这个操作线程中设置|获取值,不会干扰到其它线程。

    注意:ThreadLocal本身是存不了值得,存放数据是放在ThreadLocalMap(key为ThreadLocal)中的value

    demo示例及运行结果

    public class ThreadLocalDemo {
    
        private final static ThreadLocal<String> threadLocal = new ThreadLocal<>();
        
        public static void main(String[] args) {
            threadLocal.set("this is main Thread!");
            System.out.println("主线程获取threadLocal中的值:" + threadLocal.get());
            System.out.println(Thread.currentThread());
            new Thread(() -> {
                System.out.println(Thread.currentThread());
                System.out.println("赋值前,thread1线程获取threadLocal中的值:" + threadLocal.get());
                threadLocal.set("this is thread1!");
                System.out.println("赋值后,thread1线程获取threadLocal中的值:" + threadLocal.get());
            }).start();
            
            
            new Thread(() -> {
                System.out.println(Thread.currentThread());
                System.out.println("赋值前,thread2线程获取threadLocal中的值:" + threadLocal.get());
                threadLocal.set("this is thread2!");
                System.out.println("赋值后,thread2线程获取threadLocal中的值:" + threadLocal.get());
            }).start();
        }
    
    }

    运行结果

    主线程获取threadLocal中的值:this is main Thread!
    Thread[main,5,main]
    Thread[Thread-0,5,main]
    赋值前,thread1线程获取threadLocal中的值:null
    赋值后,thread1线程获取threadLocal中的值:this is thread1!
    Thread[Thread-1,5,main]
    赋值前,thread2线程获取threadLocal中的值:null
    赋值后,thread2线程获取threadLocal中的值:this is thread2!

    原文参考:

    一个ThreadLocal和面试官大战30个回合 https://mp.weixin.qq.com/s/JUb2GR4CmokO0SklFeNmwg

     

    思考:

    当存在多个ThreadLocal 对象,在同一个线程中,其放入的信息都在该线程中的ThreadLocalMap中,以ThreadLocal为key,设计hash表的意图就是这个吧,相互取值不干扰

  • 相关阅读:
    Mac下eclipse安装SVN插件
    python中函数参数*args和**kw的区别
    Linux下安装JDK1.8
    SpringBoot Profiles特性
    一张图讲解单机FastDFS图片服务器安装步骤(修订版)
    一张图讲解最少机器搭建FastDFS高可用分布式集群安装说明
    Zookeeper作为配置中心使用说明
    一张图秒懂微服务网络架构
    TestNG的静态方法mock的步骤
    Java中indexOf的用法
  • 原文地址:https://www.cnblogs.com/TheoryDance/p/14864254.html
Copyright © 2011-2022 走看看