美文网首页
ThreadLocal -源码

ThreadLocal -源码

作者: 王小杰at2019 | 来源:发表于2019-01-17 10:07 被阅读0次

ThreadLocal 本质上使用了一个Map key 为当前线程,value 为操作值

ThreadLocal 提供的方法几个主要的方法

  • get
  • set
  • remove

  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();
    }

     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
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }


相关文章

网友评论

      本文标题:ThreadLocal -源码

      本文链接:https://www.haomeiwen.com/subject/gpvbdqtx.html