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表的意图就是这个吧,相互取值不干扰

  • 相关阅读:
    正则获取HTML代码中img的src地址
    System.Diagnostics.Process 启动进程资源或调用外部的命令的使用
    按位取反运算符~
    Nhibernate Query By Criteria 条件查询
    Unit Test测试框架中的测试的执行顺序
    Jquery自定义插件之$.extend()、$.fn和$.fn.extend()
    如何采集QQ群中所有成员QQ号码
    Sql server使用Merge关键字做插入或更新操作
    c#类库和可移值类库的区别
    VS代码管理插件AnkhSvn
  • 原文地址:https://www.cnblogs.com/TheoryDance/p/14864254.html
Copyright © 2011-2022 走看看