关于ThreadLocal的一些理解

ThreadLocal一般是用在多线程场景里面,而多线程场景下synchronized也很常见。值得注意的是ThreadLocal与synchronized作用并不相同。
synchronized一般是多个线程访问同一个资源,为了线程安全每个线程在访问资源的时候会将资源锁起来,而ThreadLocal则是相当于将资源复制一份出来,每个线程在访问的时候只能拿到对应的资源副本,观察代码可以发现ThreadLocal其本质是一个map,他的key是当前线程所对应的资源ThreadLocal对象,而value就是设置的值。这里上代码。
public class ThreadLocalDemo {

    static {
        threadLocal = new ThreadLocal<>();
    }
    public static ThreadLocal<String> threadLocal;

    public synchronized static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            threadLocal.set("A线程变量");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            threadLocal.remove();
            System.out.println(Thread.currentThread().getName()+threadLocal.get());
        },"A线程").start();

        new Thread(() -> {
            threadLocal.set("B线程变量");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+threadLocal.get());
        },"B线程").start();
        
        
        //底层其实是一个map,k为当前线程threadLocal对象,v为对应的值

        /**
         * 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();
        //    ThreadLocal.ThreadLocalMap map = getMap(t);
        //    if (map != null)
        //        map.set(this, value);
        //    else
        //        createMap(t, value);
        //}

        /**
         * Get the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *
         * @param  t the current thread
         * @return the map
         */
        //ThreadLocal.ThreadLocalMap getMap(Thread t) {
        //    return t.threadLocals;
        //}

        /**
         * Create the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *
         * @param t the current thread
         * @param firstValue value for the initial entry of the map
         */
        //void createMap(Thread t, T firstValue) {
        //    t.threadLocals = new ThreadLocal.ThreadLocalMap(this, firstValue);
        //}
        
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值