Android进阶系列之2:HandlerThread详解

2024-03-23 19:48

本文主要是介绍Android进阶系列之2:HandlerThread详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 HandlerThread介绍

HandlerThread的本质其实就是Thread封装了Looper。默认情况下,开启一个新的线程时,不会有Looper循环。HandlerThread带个我们的功能是:当开启一个新的线程时,默认帮我们建立好消息循环。方便我们的使用。

2 HandlerThread使用例子

public class MyActivity extends Activity {private static final String TAG = "Test-Handler-Thread";private static final int MESSAGE_FROM_MAIN_THREAD = 1;private static final int MESSAGE_FROM_WORK_THREAD = 2;private HandlerThread mHandlerThread;private Handler mHandler;/*** Called when the activity is first created.*/@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mHandlerThread = new HandlerThread("Handler-Thread");mHandlerThread.start();mHandler = new Handler(mHandlerThread.getLooper()) {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case MESSAGE_FROM_MAIN_THREAD:Log.d(TAG, "msg from main thread, handleMessage in thread:" + Thread.currentThread().getName());break;case MESSAGE_FROM_WORK_THREAD:Log.d(TAG, "msg from work thread, handleMessage in thread:" + Thread.currentThread().getName());break;}}};Message msg = Message.obtain();msg.what = MESSAGE_FROM_MAIN_THREAD;mHandler.sendMessage(msg);new Thread(new Runnable() {@Overridepublic void run() {Message msg = Message.obtain();msg.what = MESSAGE_FROM_WORK_THREAD;mHandler.sendMessage(msg);}}).start();}@Overrideprotected void onDestroy() {super.onDestroy();mHandlerThread.quit();}
}

以上代码我们构建好HandlerThread以后,调用start()启动这个线程,然后分别在主线程/工作子线程发送消息,交给handler处理。
打印结果如下:

Test-Handler-Thread﹕ msg from main thread, handleMessage in thread:Handler-Thread
Test-Handler-Thread﹕ msg from work thread, handleMessage in thread:Handler-Thread

由此可见,不管是从那个线程发送的消息,handler都会统一在HandlerThread线程中执行。

注意: 在使用HandlerThread时,使用完毕以后,一定要注意调用mHandlerThread.quit(),否则HandlerThread的消息循环一直不会退出,这样会导致消息循环一直存在,这样HandlerThread就不会退出,这样,引用HandlerThread的activity也不会销毁。这样会导致内存泄漏。

3 HandlerThread源码分析

public class HandlerThread extends Thread {int mPriority;int mTid = -1;Looper mLooper;public HandlerThread(String name) {super(name);mPriority = Process.THREAD_PRIORITY_DEFAULT;}

以上代码可以看出,HandlerThread是一个线程。同时线程的优先级设置为默认优先级:Process.THREAD_PRIORITY_DEFAULT.

 protected void onLooperPrepared() {}@Overridepublic 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;}

比较精彩的是这里run()以及getLooper()方法的设计。分析这段代码之前,我们要明白HandlerThread的使命:它是一个线程,帮我们自动建立好消息循环。OK,牢记这个使命这段代码就比较好懂了。有以下两个事实:
1)由于HandlerThread会和Handler联合起来使用,Handler会通过HandlerThread的getLooper()获取looper;
2)HandlerThread作为一个线程,要启动必须调用start()方法,start()方法调用以后,CPU调度线程以后,会自行run()方法。
run()方法的执行和getLooper()方法的调用是异步的。不管谁最先被调用,必须保证在调用getLooper()的时候,looper已经被初始化,否则就要等待looper被初始化。OK,明白这些隐含的规则以后,我们再来看代码实现。
run()方法中,会首先调用Looper.prepare(),然后执行looper的初始化,这里需要同步。基于前面的分析,run()和getLooper()调用时机异步,所以run()执行的时候,一旦looper初始化,就必须调用notifyAll(),通知被getLooper()阻塞的线程继续执行。
同时在getLooper()中,获取looper时,也必须同步,如果发现looper没有初始化,就wait()阻塞等待looper初始化完毕。
一个小的注意点: 从以上分析可知,一旦HandlerThread的run()没有执行,而先调用了getLooper(),那么调用getLooper()的线程会阻塞等待HandlerThread的start()被调用来触发looper初始化。所以如果getLooper()在主线程调用,为了获取最优性能,最好先调用HandlerThread的start(),然后再去调用getLooper(),如果getLooper()被调用以后,过了很久拆掉用HandlerThread的start(),会或多或少的导致主线程被阻塞一段时间。

   public boolean quit() {Looper looper = getLooper();if (looper != null) {looper.quit();return true;}return false;}

最后quit()方法,其实就是调用looper的quit来退出消息循环。避免消息循环一直在。所以HandlerThread使用完毕以后,要调用quit方法,否则会有内存泄漏。

这篇关于Android进阶系列之2:HandlerThread详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/839356

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问