HandlerThread源码分析,Android面试官

本文详细分析了HandlerThread的构造方法、run()、quit()和quitSafe(),阐述了其在Android中如何创建Looper并进行消息处理,以及安全退出线程的方法。通过对源码的解读,揭示了HandlerThread在线程管理和消息循环中的核心作用。
摘要由CSDN通过智能技术生成

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mTv = (TextView) findViewById(R.id.tv);

initHandlerThread();

}

private void initHandlerThread() {

mHandlerThread = new HandlerThread(“xujun”);

mHandlerThread.start();

mThreadHandler = new Handler(mHandlerThread.getLooper()) {

@Override

public void handleMessage(Message msg) {

checkForUpdate();

if(isUpdate){

mThreadHandler.sendEmptyMessage(MSG_UPDATE_INFO);

}

}

};

}

/**

  • 模拟从服务器解析数据

*/

private void checkForUpdate() {

try {

//模拟耗时

Thread.sleep(1200);

mMainHandler.post(new Runnable() {

@Override

public void run() {

String result = “实时更新中,当前股票行情:%d”;

result = String.format(result, (int) (Math.random() * 5000 + 1000));

mTv.setText(Html.fromHtml(result));

}

});

} catch (InterruptedException e) {

e.printStackTrace();

}

}

@Override

protected void onResume() {

isUpdate=true;

super.onResume();

mThreadHandler.sendEmptyMessage(MSG_UPDATE_INFO);

}

@Override

protected void onPause() {

super.onPause();

isUpdate=false;

mThreadHandler.removeMessages(MSG_UPDATE_INFO);

}

@Override

protected void onDestroy() {

super.onDestroy();

mHandlerThread.quit();

mMainHandler.removeCallbacksAndMessages(null);

}

}

运行以上测试代码,将可以看到如下效果图


HandlerThread源码分析


* 官方源代码如下,是基于sdk23的,可以看到,只有一百多行代码而已*

public class HandlerThread extends Thread {

int mPriority;

int mTid = -1;

Looper mLooper;

public HandlerThread(String name) {

super(name);

mPriority = Process.THREAD_PRIORITY_DEFAULT;

}

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();

//持有锁机制来获得当前线程的Looper对象

synchronized (this) {

mLooper = Looper.myLooper();

//发出通知,当前线程已经创建mLooper对象成功,这里主要是通知getLooper方法中的wait

notifyAll();

}

//设置线程的优先级别

Process.setThreadPriority(mPriority);

//这里默认是空方法的实现,我们可以重写这个方法来做一些线程开始之前的准备,方便扩展

on

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

LooperPrepared();

Looper.loop();

mTid = -1;

}

public Looper getLooper() {

if (!isAlive()) {

return null;

}

// 直到线程创建完Looper之后才能获得Looper对象,Looper未创建成功,阻塞

synchronized (this) {

while (isAlive() && mLooper == null) {

try {

wait();

} catch (InterruptedException e) {

}

}

}

return mLooper;

}

public boolean quit() {

Looper looper = getLooper();

if (looper != null) {

looper.quit();

return true;

}

return false;

}

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;

}

}

1)首先我们先来看一下它的构造方法

public HandlerThread(String name) {

super(name);

mPriority = Process.THREAD_PRIORITY_DEFAULT;

}

public HandlerThread(String name, int priority) {

super(name);

mPriority = priority;

}

有两个构造方法,一个参数的和两个参数的,name代表当前线程的名称,priority为线程的优先级别

2)接着我们来看一下run()方法,在run方法里面我们可以看到我们会初始化一个Looper,并设置线程的优先级别

public void run() {

mTid = Process.myTid();

Looper.prepare();

//持有锁机制来获得当前线程的Looper对象

synchronized (this) {

mLooper = Looper.myLooper();

//发出通知,当前线程已经创建mLooper对象成功,这里主要是通知getLooper方法中的wait

notifyAll();

}

//设置线程的优先级别

Process.setThreadPriority(mPriority);

//这里默认是空方法的实现,我们可以重写这个方法来做一些线程开始之前的准备,方便扩展

onLooperPrepared();

Looper.loop();

mTid = -1;

}

  • 还记得我们前面我们说到使用HandlerThread的时候必须笑调用start()方法,接着才可以将我们的HandlerThread和我们的handler绑定在一起吗?其实原因就是我们是在run()方法才开始初始化我们的looper,而我们调用HandlerThread的start()方法的时候,线程会交给虚拟机调度,由虚拟机自动调用run方法

mHandlerThread.start();

mThreadHandler = new Handler(mHandlerThread.getLooper()) {

@Override

public void handleMessage(Message msg) {

checkForUpdate();

if(isUpdate){

mThreadHandler.sendEmptyMessage(MSG_UPDATE_INFO);

}

}

};

  • 这里我们为什么要使用锁机制和notifyAll();,原因我们可以从getLooper()方法中知道

public Looper getLooper() {

if (!isAlive()) {

return null;

}

// 直到线程创建完Looper之后才能获得Looper对象,Looper未创建成功,阻塞

synchronized (this) {

while (isAlive() && mLooper == null) {

try {

wait();

} catch (InterruptedException e) {

}

}

}

return mLooper;

}

总结:在获得mLooper对象的时候存在一个同步的问题,只有当线程创建成功并且Looper对象也创建成功之后才能获得mLooper的值。这里等待方法wait和run方法中的notifyAll方法共同完成同步问题。

3)接着我们来看一下quit方法和quitSafe方法

//调用这个方法退出Looper消息循环,及退出线程

public boolean quit() {

Looper looper = getLooper();

if (looper != null) {

looper.quit();

return true;

}

return false;

}

//调用这个方法安全地退出线程

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)

public boolean quitSafely() {

Looper looper = getLooper();

if (looper != null) {

looper.quitSafely();

return true;

}

return false;

}

跟踪这两个方法容易知道只两个方法最终都会调用MessageQueue的queue(boolean safe)方法

void quit(boolean safe) {

if (!mQuitAllowed) {

throw new IllegalStateException(“Main thread not allowed to quit.”);

}

synchronized (this) {

if (mQuitting) {

return;

}

mQuitting = true;

//安全退出调用这个方法

if (safe) {

removeAllFutureMessagesLocked();

} else {//不安全退出调用这个方法

removeAllMessagesLocked();

}

// We can assume mPtr != 0 because mQuitting was previously false.

nativeWake(mPtr);

}

}

不安全的会调用removeAllMessagesLocked();这个方法,我们来看这个方法是怎样处理的,其实就是遍历Message链表,移除所有信息的回调,并重置为null

跟踪这两个方法容易知道只两个方法最终都会调用MessageQueue的queue(boolean safe)方法

void quit(boolean safe) {

if (!mQuitAllowed) {

throw new IllegalStateException(“Main thread not allowed to quit.”);

}

synchronized (this) {

if (mQuitting) {

return;

}

mQuitting = true;

//安全退出调用这个方法

if (safe) {

removeAllFutureMessagesLocked();

} else {//不安全退出调用这个方法

removeAllMessagesLocked();

}

// We can assume mPtr != 0 because mQuitting was previously false.

nativeWake(mPtr);

}

}

不安全的会调用removeAllMessagesLocked();这个方法,我们来看这个方法是怎样处理的,其实就是遍历Message链表,移除所有信息的回调,并重置为null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值