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. MBProgressHUD长时间加载无法取消的解决方法

    使用MBProgressHUD时,加载网路数据,或者等待webview加载完毕,长时间的等待导致体验不佳,这时候希望点击屏幕取消加载动画效果: // MBProgressHUD.h @protocol ...

  2. css 未知子元素宽高的居中

    .parent{ position:relative; } .child{ position:absolute; left:50%; top:50%; transform:translate(-50% ...

  3. ERNIE学习笔记

    https://ai.baidu.com/forum/topic/show/954092 学习ERNIE的输入部分 输入 一共有五个部分组成,每个部分之间用分号;隔开: · token_ids:输入句 ...

  4. 智能指针分析及auto_ptr源码

    简介 C++没有内存自动回收机制,对堆内存的管理就是简单的new和delete,每次new出来的内存都需要手动delete释放.但由于忘记.流程复杂或者异常退出等,都有可能导致没有执行delete释放 ...

  5. Netty如何支持三种Reactor

    参考文献:极客时间傅健老师的<Netty源码剖析与实战>Talk is cheap.show me the code! 什么是Reactor及三种版本 反应堆设计模式(Reactor pa ...

  6. django ajax MTV与MVC 多对多创建方式

    MTV与MVC MTV模型(django): M:模型层(models.py) T:templates V:views MVC模型: M:模型层(models.py) V:视图层(views.py) ...

  7. selenium 鼠标,键盘操作

    1.打开和关闭网页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #!/usr/bin/env python # -*- coding:u ...

  8. 老贾的幸福生活day 04

    变量 变量名的规则: 变量名由字母,数字,下划线组成 变量名不能以数字开头 变量名要具有可描述性 变量名要区分大小写 变量名禁止使用python关键字 变量名不能使用中文和拼音 变量名推荐写法: 驼峰 ...

  9. Thrift Oneway是什么?

    网上很多文章,都有各种涉及使用 oneway 的,基本是一个THRIFT IDL示例接口前面加 oneway.看完之后对 oneway的理解还是很模糊,于是看了下Thrift的代码,终于搞懂了 one ...

  10. spark教程(18)-sparkSQL 自定义函数

    sparkSQL 也允许用户自定义函数,包括 UDF.UDAF,但没有 UDTF 官方 API class pyspark.sql.UDFRegistration(sparkSession)[sour ...