ThreadLocal系列-ThreadLocal源码

1.应用场景-Looper

public final class Looper {
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed)); //创建Looper
    }


    public static @Nullable Looper myLooper() {
        return sThreadLocal.get(); //获取Looper
    }
    
}

2.ThreadLocal.set

public class ThreadLocal<T> {
    public void set(T value) {
        Thread t = Thread.currentThread(); //获得线程
        ThreadLocalMap map = getMap(t); //获得线程的ThreadLocalMap
        if (map != null){
            map.set(this, value); //key是ThreadLocal本身
        } else {
            createMap(t, value);
        }
    }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals; //ThreadLocalMap是Thread的一个变量
    }
}
    

3.ThreadLocal.get 

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

4.总结 

  • 存储在线程的一个变量里,类型为ThreadLocalMap
  • ThreadLocalMap存储的是Entry
  • key是ThreadLocal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值