ThreadLocal基本原理

ThreadLocal基本原理

  1. 设置值
    public void set(T value) {
        Thread t = Thread.currentThread(); // 拿到当前线程对象
        ThreadLocalMap map = getMap(t);  // 拿到当前线程对象的ThreadLocalMap 对象
        if (map != null)
            map.set(this, value);  // 设置值,以当前ThreadLocal对象为键
        else
            createMap(t, value);
    }
  1. 获取值
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

你可能感兴趣的:(java基础)