您的位置:首页 > 移动开发 > Android开发

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

2015-12-03 22:40 531 查看

简介

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区别

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: