ThreadLocal原理

本文详细介绍了ThreadLocal的作用及其实现原理。ThreadLocal通过ThreadLocalMap与当前线程绑定,每个线程都有自己的ThreadLocalMap用于存储独立的变量副本,从而确保线程间变量隔离。文章还提供了get、set和remove方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ThreadLocal是什么?看Java源码中的描述:

 

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

 

ThreadLocal通过ThreadLocalMap与当前线程绑定到一起(如下图)。

 

 

每一个Thread对象,专门用一个ThreadLocalMap来存储自己专用的变量。ThreadLocalMap其实就跟我们平时常用的HashMap类似,能够存储Key-Value形式的数据。在这里,ThreadLocalMap的Key是一个ThreadLocal对象。

 

ThreadLocal在每次get或set操作时,都会先通过Thread.currentThread()方法来获取当前线程,再从当前线程中获取ThreadLocalMap。表面上看,ThreadLocal像是一个变量体(或者说是存储变量的容器),而实际上,它是通过Map来存储的。

 

一个ThreadLocal对象可以是多线程共享,但一个ThreadLocalMap对象却是某个线程独享的,即每一个Thread对象,都会创建一个自己专用的ThreadLocalMap,与其他Thread对象创建的ThreadLocalMap不存在相等关系。

 

当多个Thread对象共同访问同一个ThreadLocal对象时,threadLocal只是作为ThreadLocalMap的Key存在,而不作为变量的存储介质。threadLocal的set()方法和get()方法所涉及的value是存储为ThreadLocalMap的value。而ThreadLocalMap是每一个Thread各自专用的,互不相等的。这就是为什么同ThreadLocal被多线程同时访问,ThreadLocal的值却互不干扰的原理。

 

贴一下ThreadLocal的get()、set()、remove()方法的代码,从代码中看,更容易理解!

 

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to 
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * <tt>initialValue</tt> method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

 

 

基于C#开发的一个稳定可靠的上位机系统,旨在满足工业控制的需求。该系统集成了多个功能界面,如操作界面、监控界面、工艺流显示界面、工艺表界面、工艺编辑界面、曲线界面和异常报警界面。每个界面都经过精心设计,以提高用户体验和工作效率。例如,操作界面和监控界面对触摸屏友好,支持常规点击和数字输入框;工艺流显示界面能够实时展示工艺步骤并变换颜色;工艺表界面支持Excel和加密文件的导入导出;工艺编辑界面采用树形编辑方式;曲线界面可展示八组曲线并自定义纵坐标数值;异常报警界面能够在工艺流程出现问题时及时报警。此外,该系统还支持与倍福TC2、TC3和西门子PLC1200/300等下位机设备的通信,确保生产线的顺畅运行。系统参考欧洲工艺软件开发,已稳定运行多年,证明了其可靠性和稳定性。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是对C#编程有一定基础的人群。 使用场景及目标:适用于需要构建高效、稳定的工业控制系统的企业和个人开发者。主要目标是提升生产效率、确保生产安全、优化工艺流程管理和实现数据的有效管理与传输。 其他说明:文中提供了部分示例代码片段,帮助读者更好地理解具体实现方法。系统的复杂度较高,但凭借C#的强大功能和开发团队的经验,确保了系统的稳定性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值