关于 HandlerThread 这个类。可能有些人眼睛一瞟,手指放在键盘上,然后就是一阵狂敲。立即就能敲出一段段华丽的代码:

HandlerThread handlerThread = new HandlerThread("handlerThread");
handlerThread.start();Handler handler = new Handler(handlerThread.getLooper()){public void handleMessage(Message msg) {...}
};
handler.sendMessage(***);

细致一看。没问题啊(我也没说代码有问题啊),那请容许我说一句,“这代码敲也敲完了,原理懂不?”

为什么要扯这玩意。没什么理由,就是不小心看了这篇文章Android消息循环机制源代码分析。学姐说了,源代码都没看,没分析。还敢说你懂。原本还认为自己懂了点,看完这句话。顿时就不确定了。

于是,自觉打开了 AS …

前言

首先,先给各位看官打个预防针。待会要讲的东西可能有点多,有点绕。涉及的类包括有:HandlerThread、Thread、Handler、Looper、Message、MessageQueue,可能有些人已经遭不住啦,有种想要关闭网页的冲动。不要慌,刚開始我看源代码的时候我也不知道最終会牵扯这么一大串出来,但细致理一理后,事实上就是那么回事。

一、擒贼先擒王 HandlerThread

这件事情的源头都是因它而起的。不先找它先找谁。

首先,HandlerThread 是什么gui。感觉像是 Handler 和 Thread 的结合体。点进源代码一看:public class HandlerThread extends Thread {} 没什么好说的,原来是一个线程的子类。那么接下来就要看看这个 HandlerThread 究竟有什么特殊之处。

HandlerThread handlerThread = new HandlerThread("handlerThread");
handlerThread.start();

跟正常线程的创建、启动步骤一样。线程已启动,那势必会运行其 run() 方法。为了方便以下流程的分析,这里先用代码块1表示:

#HandlerThread.javapublic void run() {mTid = Process.myTid();Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid = -1;
}

当中。Looper 就代表我们常常说的消息循环,Looper.prepare() 就代表消息循环运行前的一些准备工作。

二、抓捕各种小弟(Looper、MessageQueue、Message)

既然上面已经谈到Looper。那就来看一下它的几个方法:Looper.prepare() 和 Looper.loop()。
代码块2

#Looper.javapublic 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));
}private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();
}static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
final MessageQueue mQueue;
final Thread mThread;

上面一路下来还是挺清晰的。总结一下:由于一个 Thread 仅仅能相应有一个 Looper,所以仅仅有满足条件下才会将 Looper 对象存放在类型为 ThreadLocal 的类属性里。当然在这之前还是要先 new 一个 Looper 对象,而在 Looper 的构造方法中又创建了两个对象 。分别为mQueue(消息队列)和 mThread(当前线程)。

整个 prepare 过程事实上主要是创建了三个对象:Looper、MessageQueue、Thread。
好了,Looper.prepare() 这个过程已经分析完了。

接着我们再看代码块1。里面有一段同步代码块,目的是为了获取 Looper 对象。方法跳转过去一看。原来就是将之前存进 ThreadLocal 里的Looper 对象取出 。

#Looper.javapublic static Looper myLooper() {return sThreadLocal.get();
}

接下来最关键的就是 Looper.loop() 这句代码,它也是 HandlerThread 这个类存在的价值所在。仅仅要一运行这句代码,也就代表真正的消息循环開始啦:代码块3

#Looper.javapublic static void loop() {final Looper me = myLooper();if (me == null) {throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}final MessageQueue queue = me.mQueue;// Make sure the identity of this thread is that of the local process,// and keep track of what that identity token actually is.Binder.clearCallingIdentity();final long ident = Binder.clearCallingIdentity();for (;;) {Message msg = queue.next(); // might blockif (msg == null) {// No message indicates that the message queue is quitting.return;}// This must be in a local variable, in case a UI event sets the loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}msg.target.dispatchMessage(msg);if (logging != null) {logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);}// Make sure that during the course of dispatching the// identity of the thread wasn't corrupted.final long newIdent = Binder.clearCallingIdentity();if (ident != newIdent) {Log.wtf(TAG, "Thread identity changed from 0x"+ Long.toHexString(ident) + " to 0x"+ Long.toHexString(newIdent) + " while dispatching to "+ msg.target.getClass().getName() + " "+ msg.callback + " what=" + msg.what);}msg.recycleUnchecked();}
}

这种方法的作用就是開始从消息队列中循环取出消息。那这个消息队列又从哪来的呢,还记得我们在Looper.prepare() 中创建 Looper 对象的时候在其构造方法中 new 两个对象嘛。一个 MessageQueue,一个Thread。

在这里要想使用消息队列。首先须要先获取 Looper 实例。毕竟消息队列 MessageQueue 是作为其成员属性而存在的。接着获得了消息队列的对象,并进入一个貌似死循环的控制流中。

这个 for 语句干的事情就是不断的从消息队列 MessageQueue 里取出消息,然后发送出去。

详细谁来处理这些消息立即揭晓。

以下的代码就是不断地取出消息:

#Looper.javaMessage msg = queue.next()

接下去的内容可能就须要各位看官对数据结构有点了解了,我们一步一步嵌进去看一下。代码块4

#MessageQueue.javaMessage next() {...for (;;) {if (nextPollTimeoutMillis != 0) {Binder.flushPendingCommands();}nativePollOnce(ptr, nextPollTimeoutMillis);synchronized (this) {// Try to retrieve the next message.  Return if found.final long now = SystemClock.uptimeMillis();Message prevMsg = null;Message msg = mMessages;if (msg != null && msg.target == null) {// Stalled by a barrier.  Find the next asynchronous message in the queue.do {prevMsg = msg;msg = msg.next;} while (msg != null && !msg.isAsynchronous());}if (msg != null) {if (now < msg.when) {// Next message is not ready.  Set a timeout to wake up when it is ready.nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);} else {// Got a message.mBlocked = false;if (prevMsg != null) {prevMsg.next = msg.next;} else {mMessages = msg.next;}msg.next = null;if (false) Log.v("MessageQueue", "Returning message: " + msg);return msg;}} else {// No more messages.nextPollTimeoutMillis = -1;}// Process the quit message now that all pending messages have been handled.if (mQuitting) {dispose();return null;}// If first time idle, then get the number of idlers to run.// Idle handles only run if the queue is empty or if the first message// in the queue (possibly a barrier) is due to be handled in the future.if (pendingIdleHandlerCount < 0&& (mMessages == null || now < mMessages.when)) {pendingIdleHandlerCount = mIdleHandlers.size();}if (pendingIdleHandlerCount <= 0) {// No idle handlers to run.  Loop and wait some more.mBlocked = true;continue;}if (mPendingIdleHandlers == null) {mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];}mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);}...}
}

其他能够先无论。我们直接跳转到 synchronized 这同步代码块里。我们看到Message msg = mMessage; 这个 mMessage 对象就是一个消息 Message,仅仅只是这个 Message 类里面附带了一种数据结构:链表。我们最好还是看一下这个类:

public final class Message implements Parcelable {...// sometimes we store linked lists of these things/*package*/ Message next;   ...
}

不难看出。Message 类中包括了一个 Message 类型的属性,作用就是指向下一条消息。依次类推,最終形成一个链表结构。仅仅只是这里链表中的消息是要经过特殊处理的,并非每进来一条消息就直接追加到尾部。由于 Android 系统中的消息是有时间机制的。每条消息都会附加一个时间。这也是handler.sendMessageDelayed() 存在的意义。

接着看代码块4,先是对 msg 和 msg.target 进行推断,仅仅要链表中中的消息不为空,同一时候消息的触发时间小于当前系统的时间,那么这个消息就会被取出来作为待发送的对象。这里 msg.target 是非常重要的,我们之所以能 handleMessage 全靠它,以下会分析到。

然后回到代码块3,通过

Message msg = queue.next(); // might block

拿到消息后。再由 msg.target 将消息分发出去

msg.target.dispatchMessage(msg);

那这个 msg.target 究竟是个什么东西。看属性定义

/*package*/ Handler target;

竟然是一个 Handler,通过它将消息分发出去。我们再看一下是如何分发的:

#Handler.java/*** Handle system messages here.*/
public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}
}

是不是有种茅塞顿开的感觉。

在这我就直接透漏一下,Message 中的 callback 事实上就是一个 Runnable 对象。handleCallback(msg); 就是运行其 run() 方法。

这也是为什么我们能够通过 handler.post(new Runnable(){...})来发送消息,事实上就是把Runnable对象赋给了Message的Callback 属性。

而假设是正常的 handler.sendMessage(),那么肯定就是运行以下的语句咯。我们能够在创建 Handler 对象的时候指定一个回调接口 Callback。

当然不指定也没事。我们最終还是能够通过 handleMessage(msg) 来获取待处理的消息。最后,我们还是要对这条消息进行回收重用的嘛msg.recycleUnchecked();

好了,关于Looper.prepare() 和 Looper.loop() 这两个方法就介绍到这。

我们再来补充一下,消息队列之所以有消息,那肯定得有谁提供瑟。答案就是 Handler。我们常常的操作就是handler.sendMessage(msg);代码块5

#Handler.javapublic final boolean sendMessage(Message msg) {return sendMessageDelayed(msg, 0);
}public final boolean sendMessageDelayed(Message msg, long delayMillis){if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}public boolean sendMessageAtTime(Message msg, long uptimeMillis) {MessageQueue queue = mQueue;if (queue == null) {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);return false;}return enqueueMessage(queue, msg, uptimeMillis);
}private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {msg.target = this;if (mAsynchronous) {msg.setAsynchronous(true);}return queue.enqueueMessage(msg, uptimeMillis);
}
#MessageQueue.javaboolean enqueueMessage(Message msg, long when) {if (msg.target == null) {throw new IllegalArgumentException("Message must have a target.");}if (msg.isInUse()) {throw new IllegalStateException(msg + " This message is already in use.");}synchronized (this) {if (mQuitting) {IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");Log.w("MessageQueue", e.getMessage(), e);msg.recycle();return false;}msg.markInUse();msg.when = when;Message p = mMessages;boolean needWake;if (p == null || when == 0 || when < p.when) {// New head, wake up the event queue if blocked.msg.next = p;mMessages = msg;needWake = mBlocked;} else {// Inserted within the middle of the queue.  Usually we don't have to wake// up the event queue unless there is a barrier at the head of the queue// and the message is the earliest asynchronous message in the queue.needWake = mBlocked && p.target == null && msg.isAsynchronous();Message prev;for (;;) {prev = p;p = p.next;if (p == null || when < p.when) {break;}if (needWake && p.isAsynchronous()) {needWake = false;}}msg.next = p; // invariant: p == prev.nextprev.next = msg;}// We can assume mPtr != 0 because mQuitting is false.if (needWake) {nativeWake(mPtr);}}return true;
}

我认为我也没什么好说的,赤裸裸的将流程一步一步的贴出来。一句话,对传入进来的 Message 进行封装,什么 msg.when、msg.target。通通在这里搞定。

如今细致回忆 Looper.loop() 里面对 msg 的处理。之前的各种❓是不就烟消云散啦。后面就顶多就是将消息加入到消息链表中。同一时候如我前面所说的那样。要依据 msg.when 的时间插入到合适的位置中去。

总结

至此,整个消息循环机制就分析完啦。原始代码:

HandlerThread handlerThread = new HandlerThread("handlerThread");
handlerThread.start();Handler handler = new Handler(handlerThread.getLooper()){public void handleMessage(Message msg) {...}
};
handler.sendMessage(***);

再看一下详细操作流程:

  1. handlerThread.start() -> Looper.prepare() -> Looper.loop() -> queue.next() -> msg.target.dispatchMessage(msg) -> handleMessage(msg)
  2. handler.sendMessage(msg) -> queue.enqueueMessage(msg)

由于上面的一切操作都是在一个新线程的 run() 方法中运行,所以不会堵塞 UI 线程。分析完成。
这时可能有些人就站出来了,这 HandlerThread 感觉也没啥啊,我直接用 Thread 也能够搞定一切。设想一下,加入如今有10个后台任务须要运行,依照传统的做法就是运行10遍 new Thread(某个Runnable对象).start() 首先你是创建了10个匿名对象。这资源消耗多少暂且不说。你还不能非常好的控制它们。这样非常easy造成内存泄漏。若是将这些后台任务打包成成一个个 Message 然后再发送出去。首先是线程能够得到重用,再者我们还能够 remove 掉消息队列中的消息,再一定程度上避免了内存泄漏。

好了,该说的都说完了。可能须要各位看官自己脑补一下、消化一下。

转载于:https://www.cnblogs.com/cxchanpin/p/7228507.html

Android HandlerThread 消息循环机制之源代码解析相关推荐

  1. Android的消息循环机制:Handler

    前言 Android的消息机制主要是指Handler的运行机制,对于大家来说Handler已经是轻车熟路了,可是真的掌握了Handler?本文主要通过几个问题围绕着Handler展开深入并拓展的了解. ...

  2. android 结束if循环_Android Handler 消息循环机制

    前言 一问起Android应用程序的入口,很多人会说是Activity中的onCreate方法,也有人说是ActivityThread中的静态main方法.因为Java虚拟机在运行的时候会自动加载指定 ...

  3. android的消息队列机制

    android下的线程,Looper线程,MessageQueue,Handler,Message等之间的关系,以及Message的send/post及Message dispatch的过程. Loo ...

  4. android 消息循环机制--looper handler

    Looper类说明   Looper 类用来为一个线程跑一个消息循环. 线程在默认情况下是没有消息循环与之关联的,Thread类在run()方法中的内容执行完之后就退出了,即线程做完自己的工作之后就结 ...

  5. java handlerthread_深入Android HandlerThread 使用及其源码完全解析

    本篇我们将来给大家介绍HandlerThread这个类,以前我们在使用线程执行一个耗时任务时总会new一个Thread的线程去跑,当任务执行完后,线程就会自动被销毁掉,如果又由新的任务,我们又得新建线 ...

  6. 详谈Windows消息循环机制

    一直对windows消息循环不太清楚,今天做个详细的总结,有说错的地方,请务必指出. 用VS2017新建一个win32 Application的默认代码如下: 这里有几个概念,容易混淆: 1.系统: ...

  7. Windows消息循环机制详细概述

    首先来了解几个基本概念: 消息:在了解什么是消息先来了解什么是事件.事件可分为几种,由输入设备触发的,比如鼠标键盘等等.由窗体控件触发的,比如button控件,file菜单等.还有就是来自Window ...

  8. [Android] android的消息队列机制

    2019独角兽企业重金招聘Python工程师标准>>> android下的线程,Looper线程,MessageQueue,Handler,Message等之间的关系,以及Messa ...

  9. RocketMQ:消息ACK机制源码解析

    消息消费进度 概述 消费者消费消息过程中,为了避免消息的重复消费,应将消息消费进度保存起来,当其他消费者再对消息进行消费时,读取已消费的消息偏移量,对之后的消息进行消费即可. 消息模式分为两种: 集群 ...

  10. c#中使用消息循环机制发送接收字符串的方法和数据类型转换

    在定义消息时忘记了用户可定义消息的边界值,在网上一阵疯找后来发现是const int WM_USER = 0x400.接着是SendMessage的lParam类型不能决定(默认是IntPtr),我想 ...

最新文章

  1. IPSec ***基于ASA的配置(思科)
  2. 0基础学python难吗-0基础学Python有多难?该怎么入门?
  3. Maven 项目的 org.junit.Test 获取不到(转载)
  4. 移动办公计算机,最适合移动办公的三款掌上电脑点评
  5. DeepMind 用 GAN 虚构视频真假难辨【智能行业热点】(2019.7.22)
  6. OSPF外部实验详解
  7. 搜索框键盘抬起事件2
  8. 计算机音乐新年好呀,新年好呀新年好 伴奏
  9. MySQL 数据库规范
  10. 安卓电子书格式_求把 EPUB 转换成 MOBI 的电子书格式转换工具
  11. python实现topsis法
  12. IT服务管理流程控制主要绩效指标有哪些?
  13. Python-argparse库基本使用方法和add_argument() 参数详解
  14. 电脑打开网络没有WiFi列表
  15. 个人博客和微信公众号
  16. python房价预测模型_python随机森林房价预测
  17. oracle 近一年,华为Mate 20 Pro发布近一年,仍受追捧,四个方面告诉你原因
  18. Android 悬浮窗口(及解决6.0以上无法显示问题)
  19. 不怕千招会,就怕一招精,学编程不要盲目跟风
  20. 日语在线翻译网站大集合- -

热门文章

  1. 字符串缓冲区和字符串构造器
  2. python 爬poj.org的题目
  3. Python nose测试工具报ImportError: No Module named 错误
  4. Linux--进程组 作业 会话 守护(精灵)进程
  5. 此博客记录我的日常学习过程
  6. iOS 更改导航栏返回button文字
  7. U-boot在S3C2440上的移植详解(二)
  8. 常用响应式web UI框架搜集整理
  9. 【Thinking In Java】笔记之二 控制执行流程
  10. LOJ2420「NOIP2015」神奇的幻方