一、ThreadLocal回顾

ThreadLocal对象用于在同一个线程中传递数据,避免显式的在方法中传参。

每个线程中保存了ThreadLocalMap对象,ThreadLocalMap对象的key就是ThreadLocal对象本身,value就是当前线程的值。

看下ThreadLocal的get方法

public T get() {
        //当前线程
        Thread t = Thread.currentThread();
        //获取当前线程的ThreadLocalMap对象
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //获取该ThreadLocal对象的value
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        //设置初始值
        return setInitialValue();
    }
    
    //获取当前线程的ThreadLocalMap对象
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
View Code

相关文章:

  • 2021-07-22
  • 2021-04-03
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
猜你喜欢
  • 2022-01-20
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案