Android ThreadLocal类浅析



前言

  • ThreadLocal在哪出现的?
  • ThreadLocal到底是个啥东西
  • ThreadLoca在Android线程消息模型中作用是啥?
  • 等等。。。

学习目标

  • 了解ThreadLoca类是个啥东西以及他在线程消息模型中扮演的角色,它的作用。

代码介绍

  • 最近在研究Android线程消息模型时,在Lopper.prepare()中发现了这么一行代码:
    public static void prepare() {
        prepare(true);
    }

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

可以看到这个有个判断: 
 if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
看这个抛出的异常字面意思是说“在一个线程中只允许存在一个looper对象”。即就是判断线程中是否已经存在looper。
我们都知道Looper.prepare()是可以让一个work thread 升级为带有消息队列MQ的消息线程的,升级的具体这里暂不多说。
怀着好奇心,我又继续查看ThreadLocal.get()方法,于是又看到了这么一段代码:
    public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值