Android进程和线程 --消息队列模型--Looper (2)(2015-12-02 19:41)

简介

Looper()  在(1)中已经有了基本的介绍

Looper类:

public final class Looper {
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper; 
    final MessageQueue mQueue;
    final Thread mThread;

Looper.prepare() 生成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是存放在ThreadLocal 对象中的。 ThreadLocal 对象存的作用域是本地线程。详细的请参看ThreadLocal的知识点。

接着使用Looper.loop()来循环去除MessageQueue中的Message进行相应的处理代码如下

     public static void loop() {
        final Looper me = myLooper();
        ...
        final MessageQueue queue = me.mQueue;
        for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        msg.target.dispatchMessage(msg);
        ...
        msg.recycleUnchecked();
    }
}
  • 首先获取自身Looper
  • 取出消息队列
  • for循环中next去除消息
  • dispatchMessage分派消息
  • msg.target为handle.

UI线程中的Looper()

  • 准备方法不一样
  • 函数名为prepareMainLooper()

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
  • 调用自身prepare

  • 变量sMainLooper
  • sMainLooper定义 private static Looper sMainLooper;
  • 可以看到是static变量 全局共享的 并使用sMainLooper指向Looper()
  • 可调用getMainLooper()获取主线程的looper.

主线程和子线程的looper区别
这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值