Java基础-ThreadLocal初识

本文深入解析了ThreadLocal在多线程环境中的应用,介绍了其如何为每个线程提供独立的变量副本,避免了线程间的数据冲突。同时,详细阐述了ThreadLocal的内部实现机制,包括其如何通过类似Map的结构存储数据,以及set和get方法的工作原理。

ThreadLocal 介绍

本地线程,提供了线程的局部变量,针对每个线程,都会创建自己的变量副本。

ThreadLocal 使用

主要用于在多线程环境下,单个线程在运行过程中都可能用到一些值时,可以使用ThreadLocal,比如:
在这里插入图片描述
上述图片中,object 对象作为一个参数分别传入到 method1,method2,method3。此时可以使用ThreadLocal,将object放入到ThreadLocal中。

private static ThreadLocal<Object> threadLocalObject = new ThreadLocal<>();

然后提供getter,setter方法,可以在整个线程调用过程中使用。

ThreadLocal 内部实现

在这里插入图片描述
内部类似于Map的格式存储,Map<Thread,Map<ThreadLocal,Object>>.
首先通过当前线程获取到entry节点,然后通过threadLocal获取到Object。


    /**
     * 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();
        // 通过当前线程获取到ThreadLocaMap然后,如果map不为空,则将this(ThreadLocal)和value放入map中。
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    /**
     * 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();
        // 通过当前线程获取到ThreadLocaMap
        ThreadLocalMap map = getMap(t);
        if (map != null) {
        	// 通过ThreadMap获取entry的,然后通过entry获取到当前值value
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值