码迷,mamicode.com
首页 > 其他好文 > 详细

ThreadLocal 理解

时间:2018-11-15 01:27:11      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:value   war   result   entry   this   creat   pre   lse   read   

 主要方法

 public void set(T value);

public T get();

 private T setInitialValue();

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

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);   //以当前线程的ThreadLocal为key 取得值
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }


private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

 

ThreadLocal 理解

标签:value   war   result   entry   this   creat   pre   lse   read   

原文地址:https://www.cnblogs.com/unclehu/p/9961277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!