handlerThread产生背景:

开启Thread子线程进行耗时操作,多次创建和销毁线程是很耗系统资源的。

handlerThread是什么?

handler + thread + looper

它其实也是一个线程,只是跟Thread是有区别的,它是一个thread内部有looper,

handlerThread的特点:

  • 它本质上是一个线程,它继承了Thread。
  • 它有自己的内部Looper对象,可以进行looper循环。
  • 通过获取HandlerThread的looper对象传递给Handler对象,可以在handleMessage方法中执行异步任务。
  • 优点是不会阻塞,减少了对性能的损耗,缺点是不能同时进行多任务的处理,需要等待进行处理,处理效率较低。
  • 与线程池注重并发不同,HandlerThread是一个串行队列【也就是任务必须一个个执行,只有一个执行完了才会执行下一个】,HandlerThread背后只有一个线程。

handlerThread源码解析:

先贴一下它的完整源码:

/**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper; public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
} /**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
} /**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
} @Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
} /**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
} // If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
} /**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
} /**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
} /**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}

以上就是它的完整源码,挺少的,但是设计很精妙,先来看一下它的类注解:

其中它就是继承Thread,很明显就是一个线程,接着来往下分析:

通过下面这句代码就可以知道:

接着看一下线程最核心的run()方法:

最后执行loop方法:

而看一下getLooper()方法:

最后再看一下跟退出相关的方法:

其中安全的退出效率肯定没有直接退出效率高。

异步消息处理机制相关面试问题-handlerThread面试问题详解的更多相关文章

  1. 异步消息处理机制相关面试问题-intentservice面试问题详解

    IntentService是什么? IntentService是继承并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService方法和启动传统的S ...

  2. 异步消息处理机制相关面试问题-handler面试问题详解

    什么是handler? 这个异常应该也就是引出handler的原因,也就是默认在非UI线程中是无法去更新UI的东东滴,那到底什么上handler呢? handler通过发送和处理Message和Run ...

  3. 异步消息处理机制相关面试问题-AsyncTask面试问题详解

    什么是AsyncTask: 它本质上是一个封装了线程池和handler的异步框架. AsyncTask的使用方法: 三个参数: 五个方法: AsyncTask的内部原理: AsyncTask的注意事项 ...

  4. 【转】Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 很多人面试肯定都被问到过,请问Andr ...

  5. Android 异步消息处理机制 让你在深入了解 Looper、Handler、Message之间的关系

    转载请注明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 非常多人面试肯定都被问到过,请问And ...

  6. Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系

    转自:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 很多人面试肯定都被问到过,请问Android中的 ...

  7. 【转载】Android异步消息处理机制详解及源码分析

    PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbob ...

  8. Android 异步消息处理机制终结篇 :深入理解 Looper、Handler、Message、MessageQueue四者关系

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.概述 我们知道更新UI操作我们需要在UI线程中操作,如果在子线程中更新UI会发生异常可能导致崩溃,但是在UI线程中进行耗时操作又会导致ANR,这 ...

  9. Android多线程----异步消息处理机制之Handler详解

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

随机推荐

  1. 多线程基础知识---join方法

    join方法的作用 thread.join()方法用于把指定的线程加入到当前线程中,把当前线程的CPU执行时间让给另一个线程.比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继 ...

  2. vlan端口类型

    交换机三种链路类型:access.trunk.hybrid. access类型只属于一个VLAN,一般用于连接计算机端口. trunk类型可以允许多个vlan通过,可以接收和发送多个vlan的报文,一 ...

  3. Linux下使用 minicom 自动重复发送数据的实现

    目录 在minicom中添加脚本路径 编写脚本 执行脚本 一个项目里要用的设备需要用串口来模拟传感器来测试,还是Linux下的. 串口助手cutecom很好用,但是不能定时发送数据. 所以用下面这个脚 ...

  4. 【环境搭建】Angular (含Hello World)

    一.环境安装 1.安装node.js 下载路径:https://nodejs.org/en/download/ 命令行验证: 2.安装ts.cli ts: npm install -g typescr ...

  5. win7安装mongodb3.6

    1. 下载 https://www.mongodb.com/download-center/enterprise 选择合适平台点击下载 2. 安装mongodb 在win7系统安装mongodb需要v ...

  6. Thinkphp5 自定义上传文件名

    这几天在做tp5的上传文件模块,项目需求是要把文件名在上传之后修改为 用户名+原文件名的组合形式,在网上找了一会儿发现好像没有类似的文章...只好自己去研究研究了. 之前查看过看云上面的官方手册,文件 ...

  7. 【Life】 今天的思考

    今天一个实习生来问我问题,他要用python操作outlook发送邮件,代码是从网上找的. 在其他人的电脑上可以成功运行,但在他的电脑上就失败. 处理过程 (1)我查看了他method里的代码, 发现 ...

  8. JDK1.8新特性(二):Collectors收集器类

    一. 什么是Collectors? Java 8 API添加了一个新的抽象称为流Stream,我们借助Stream API可以很方便的操作流对象. Stream中有两个方法collect和collec ...

  9. kafka运维填坑

    转载自:https://www.jianshu.com/p/d2cbaae38014 前提: 只针对Kafka 0.9.0.1版本; 说是运维,其实偏重于问题解决; 大部分解决方案都是google而来 ...

  10. 序列化和反序列化在浏览器和 Web 服务器之间传递的数据、加密解密

    js中数组不能传递到后台,需进行json序列化: var data = new Array(); data.push({para1:name,para2:answer}); string data = ...