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. 【ABAP系列】SAP ABAP 为表维护生成器创建事务代码

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP 为表维护生成器 ...

  2. centos 自动挂载ISO

    创建挂载点并挂载光盘mkdir -p /media/cdrommount -t iso9660 -o loop /usr/ison/centos.iso /media/cdrom 设置开机自动挂载:方 ...

  3. 【POJ - 3045】Cow Acrobats (贪心)

    Cow Acrobats Descriptions 农夫的N只牛(1<=n<=50,000)决定练习特技表演. 特技表演如下:站在对方的头顶上,形成一个垂直的高度. 每头牛都有重量(1 & ...

  4. 喜欢听DJ的朋友可以自己用下,别传播

    // ==UserScript== // @icon http://djkk.com/favicon.ico // @name DJKK Downloader // @namespace http:/ ...

  5. HTTP 状态代码的完整列表

    1xx(临时响应) 用于表示临时响应并需要请求者执行操作才能继续的状态代码. 代码 说明 100(继续) 请求者应当继续提出请求.服务器返回此代码则意味着,服务器已收到了请求的第一部分,现正在等待接收 ...

  6. mysql查询出数据更新到另一张表

    公司今天有个需求,大体意思就是把一个表的玩家游戏场数统计出来,然后赋值到另一张表的字段上,说白了就是两张表,但是查询出来的玩家账号和次数是多条,尝试很多种写法都没用,最后用了最笨的方式解决. -- - ...

  7. Redis分布式锁解决抢购问题

    转:https://segmentfault.com/a/1190000011421467 废话不多说,首先分享一个业务场景-抢购.一个典型的高并发问题,所需的最关键字段就是库存,在高并发的情况下每次 ...

  8. 嵌入式Linux的计划任务,发送请求记录

  9. C#实现鼠标滚筒缩放界面的效果

    elementCanvas继承UserControl 声明属性: #region 缩放属性添加 float ratio = 1.0f; public float Ratio { set { ratio ...

  10. Flink的时间类型和watermark机制

    一FlinkTime类型 有3类时间,分别是数据本身的产生时间.进入Flink系统的时间和被处理的时间,在Flink系统中的数据可以有三种时间属性: Event Time 是每条数据在其生产设备上发生 ...