美文网首页
ThreadLocal

ThreadLocal

作者: 我会四歩篮 | 来源:发表于2018-11-25 17:56 被阅读2次

    每一个线程都有一个ThreadLocalMap的存储结构,一个ThreadLocal变量都会被每个线程复制一份线程私有的变量,
    通过Set(Object)对ThreadLocal变量赋值,通过get()获取值


    public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map !=null)
    map.set(this, value);
    else
    createMap(t, value);
    }

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

    相关文章

      网友评论

          本文标题:ThreadLocal

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