@author:小马快跑
@email:[email protected]
@github:https://github.com/crazyqiang
HandlerThread的介绍及用法
HandlerThread继承自Thread,内部实现了初始化了Looper,并创建了消息队列,接着调用了Looper.loop()开启了消息循环,这样HandlerThread就可以处理通过Handler传递过来的Message了,因为HandlerThread中的run方法是无限循环,当有消息过来时处理消息,没有消息时就会阻塞。当明确不需要HandlerThread时,可以调用quit或者quitSafely (API 18以上使用)来尝试终止线程。
先看实现的一个效果图:
返回结果 | HandlerThread | 备注 |
---|---|---|
Looper | getLooper() | 返回和HandlerThread关联的Looper |
int | getThreadId() | 返回HandlerThread线程的标识符,参见Process.myTid() |
boolean | quit() | 立即停止Looper的循环,即使messageQueue中有消息也不再处理,在调用此方法后,任何传递Message的方法 (如sendMessage(Message)) 都将失败并返回false |
boolean | quitSafely() | 当messageQueue中没有Message后,在调用此方法后立即终止Looper,任何传递Message的方法 (如sendMessage(Message)) 都将失败并返回false |
void | run() | 如果HandlerThread使用单独的Runnable来构造,将执行此方法 |
HandlerThread源码分析
public class HandlerThread extends Thread { int mPriority; int mTid = -1; Looper mLooper; //初始化HandlerThread public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } //初始化HandlerThread public HandlerThread(String name, int priority) { super(name); mPriority = priority; } protected void onLooperPrepared() { } @Override public void run() { mTid = Process.myTid(); //调用Looper.prepare()初始化Looper 并把Looper放到sThreadLocal中,sThreadLocal可以在不同线程中保存对象副本 //在Looper的构造方法中就初始化了一个messageQueue,用来存放传入的消息 Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); //开始循环从messageQueue中取出消息并处理消息,无消息会阻塞,有消息来时就会唤醒 Looper.loop(); mTid = -1; } //返回的即是run方法中产生的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; } //立即停止Looper的循环,即使messageQueue中有消息也不再处理,在调用此方法后,任何传递Message的 //方法 (如sendMessage(Message)) 都将失败并返回false public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; } //当messageQueue中没有Message后,在调用此方法后立即终止Looper,任何传递Message的 //方法 (如sendMessage(Message)) 都将失败并返回false public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; } public int getThreadId() { return mTid; } }
源码很简单,首先HandlerThread继承了Thread,所以HandlerThread本质上还是一个线程,只不过在run()方法中又初始化了Looper和MessageQueue,这样当外界通过Handler向HandlerThread传入消息后,HandlerThread就会取出消息并处理消息,当没有消息时就会阻塞。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦