Android實(shí)例HandlerThread源碼分析
HandlerThread 簡(jiǎn)介:
我們知道Thread線程是一次性消費(fèi)品,當(dāng)Thread線程執(zhí)行完一個(gè)耗時(shí)的任務(wù)之后,線程就會(huì)被自動(dòng)銷毀了。如果此時(shí)我又有一
個(gè)耗時(shí)任務(wù)需要執(zhí)行,我們不得不重新創(chuàng)建線程去執(zhí)行該耗時(shí)任務(wù)。然而,這樣就存在一個(gè)性能問(wèn)題:多次創(chuàng)建和銷毀線程是很耗
系統(tǒng)資源的。為了解這種問(wèn)題,我們可以自己構(gòu)建一個(gè)循環(huán)線程Looper Thread,當(dāng)有耗時(shí)任務(wù)投放到該循環(huán)線程中時(shí),線程執(zhí)行耗
時(shí)任務(wù),執(zhí)行完之后循環(huán)線程處于等待狀態(tài),直到下一個(gè)新的耗時(shí)任務(wù)被投放進(jìn)來(lái)。這樣一來(lái)就避免了多次創(chuàng)建Thread線程導(dǎo)致的
性能問(wèn)題了。也許你可以自己去構(gòu)建一個(gè)循環(huán)線程,但我可以告訴你一個(gè)好消息,Aandroid SDK中其實(shí)已經(jīng)有一個(gè)循環(huán)線程的框架
了。此時(shí)你只需要掌握其怎么使用的就ok啦!當(dāng)然就是我們今天的主角HandlerThread啦!接下來(lái)請(qǐng)HandlerThread上場(chǎng),鼓掌~~
HandlerThread的父類是Thread,因此HandlerThread其實(shí)是一個(gè)線程,只不過(guò)其內(nèi)部幫你實(shí)現(xiàn)了一個(gè)Looper的循環(huán)而已。那么我們
先來(lái)了解一下Handler是怎么使用的吧!
HandlerThread使用步驟:
1.創(chuàng)建實(shí)例對(duì)象
HandlerThread handlerThread = new HandlerThread("handlerThread");
以上參數(shù)可以任意字符串,參數(shù)的作用主要是標(biāo)記當(dāng)前線程的名字。
2.啟動(dòng)HandlerThread線程
handlerThread.start();
到此,我們就構(gòu)建完一個(gè)循環(huán)線程了。那么你可能會(huì)懷疑,那我怎么將一個(gè)耗時(shí)的異步任務(wù)投放到HandlerThread線程中去執(zhí)行呢?當(dāng)然是有辦法的,接下來(lái)看第三部。
3.構(gòu)建循環(huán)消息處理機(jī)制
Handler subHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { //實(shí)現(xiàn)自己的消息處理 return true; } });
第三步創(chuàng)建一個(gè)Handler對(duì)象,將上面HandlerThread中的looper對(duì)象最為Handler的參數(shù),然后重寫Handler的Callback接口類中的
handlerMessage方法來(lái)處理耗時(shí)任務(wù)。
總結(jié):以上三步順序不能亂,必須嚴(yán)格按照步驟來(lái)。到此,我們就可以調(diào)用subHandler以發(fā)送消息的形式發(fā)送耗時(shí)任務(wù)到線程
HandlerThread中去執(zhí)行。言外之意就是subHandler中Callback接口類中的handlerMessage方法其實(shí)是在工作線程中執(zhí)行的。
HandlerThread實(shí)例:
package com.example.handlerthread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private Handler mSubHandler; private TextView textView; private Button button; private Handler.Callback mSubCallback = new Handler.Callback() { //該接口的實(shí)現(xiàn)就是處理異步耗時(shí)任務(wù)的,因此該方法執(zhí)行在子線程中 @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 0: Message msg1 = new Message(); msg1.what = 0; msg1.obj = java.lang.System.currentTimeMillis(); mUIHandler.sendMessage(msg1); break; default: break; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); button = (Button) findViewById(R.id.button); HandlerThread workHandle = new HandlerThread("workHandleThread"); workHandle.start(); mSubHandler = new Handler(workHandle.getLooper(), mSubCallback); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //投放異步耗時(shí)任務(wù)到HandlerThread中 mSubHandler.sendEmptyMessage(0); } }); } }
HandlerThread源碼分析
HandlerThread構(gòu)造方法
/** * 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 { //線程優(yōu)先級(jí) int mPriority; //當(dāng)前線程id int mTid = -1; //當(dāng)前線程持有的Looper對(duì)象 Looper mLooper; //構(gòu)造方法 public HandlerThread(String name) { //調(diào)用父類默認(rèn)的方法創(chuàng)建線程 super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } //帶優(yōu)先級(jí)參數(shù)的構(gòu)造方法 public HandlerThread(String name, int priority) { super(name); mPriority = priority; } ............... }
分析:該類開頭就給出了一個(gè)描述:該類用于創(chuàng)建一個(gè)帶Looper循環(huán)的線程,Looper對(duì)象用于創(chuàng)建Handler對(duì)象,值得注意的是在創(chuàng)建Handler
對(duì)象之前需要調(diào)用start()方法啟動(dòng)線程。這里可能有些人會(huì)有疑問(wèn)?為啥需要先調(diào)用start()方法之后才能創(chuàng)建Handler呢?后面我們會(huì)解答。
上面的代碼注釋已經(jīng)很清楚了,HandlerThread類有兩個(gè)構(gòu)造方法,不同之處就是設(shè)置當(dāng)前線程的優(yōu)先級(jí)參數(shù)。你可以根據(jù)自己的情況來(lái)設(shè)置優(yōu)先
級(jí),也可以使用默認(rèn)優(yōu)先級(jí)。
HandlerThrad的run方法
public class HandlerThread extends Thread { /** * Call back method that can be explicitly overridden if needed to execute some * setup before Looper loops. */ protected void onLooperPrepared() { } @Override public void run() { //獲得當(dāng)前線程的id mTid = Process.myTid(); //準(zhǔn)備循環(huán)條件 Looper.prepare(); //持有鎖機(jī)制來(lái)獲得當(dāng)前線程的Looper對(duì)象 synchronized (this) { mLooper = Looper.myLooper(); //發(fā)出通知,當(dāng)前線程已經(jīng)創(chuàng)建mLooper對(duì)象成功,這里主要是通知getLooper方法中的wait notifyAll(); } //設(shè)置當(dāng)前線程的優(yōu)先級(jí) Process.setThreadPriority(mPriority); //該方法實(shí)現(xiàn)體是空的,子類可以實(shí)現(xiàn)該方法,作用就是在線程循環(huán)之前做一些準(zhǔn)備工作,當(dāng)然子類也可以不實(shí)現(xiàn)。 onLooperPrepared(); //啟動(dòng)loop Looper.loop(); mTid = -1; } }
分析:以上代碼中的注釋已經(jīng)寫得很清楚了,以上run方法主要作用就是調(diào)用了Looper.prepare和Looper.loop構(gòu)建了一個(gè)循環(huán)線程。值得一提的
是,run方法中在啟動(dòng)loop循環(huán)之前調(diào)用了onLooperPrepared方法,該方法的實(shí)現(xiàn)是一個(gè)空的,用戶可以在子類中實(shí)現(xiàn)該方法。該方法的作用是
在線程loop之前做一些初始化工作,當(dāng)然你也可以不實(shí)現(xiàn)該方法,具體看需求。由此也可以看出,Google工程師在編寫代碼時(shí)也考慮到代碼的可擴(kuò)展性。牛B!
HandlerThread的其他方法
getLooper獲得當(dāng)前線程的Looper對(duì)象
/** * 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() { //如果線程不是存活的,則直接返回null if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. //如果線程已經(jīng)啟動(dòng),但是Looper還未創(chuàng)建的話,就等待,知道Looper創(chuàng)建成功 synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
分析:其實(shí)方法開頭的英文注釋已經(jīng)解釋的很清楚了:該方法主要作用是獲得當(dāng)前HandlerThread線程中的mLooper對(duì)象。
首先判斷當(dāng)前線程是否存活,如果不是存活的,這直接返回null。其次如果當(dāng)前線程存活的,在判斷線程的成員變量mLooper是否為null,如果為
null,說(shuō)明當(dāng)前線程已經(jīng)創(chuàng)建成功,但是還沒來(lái)得及創(chuàng)建Looper對(duì)象,因此,這里會(huì)調(diào)用wait方法去等待,當(dāng)run方法中的notifyAll方法調(diào)用之后
通知當(dāng)前線程的wait方法等待結(jié)束,跳出循環(huán),獲得mLooper對(duì)象的值。
總結(jié):在獲得mLooper對(duì)象的時(shí)候存在一個(gè)同步的問(wèn)題,只有當(dāng)線程創(chuàng)建成功并且Looper對(duì)象也創(chuàng)建成功之后才能獲得mLooper的值。這里等待方法wait和run方法中的notifyAll方法共同完成同步問(wèn)題。
quit結(jié)束當(dāng)前線程的循環(huán)
/** * 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; } //安全退出循環(huán) public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }
分析:以上有兩種讓當(dāng)前線程退出循環(huán)的方法,一種是安全的,一中是不安全的。至于兩者有什么區(qū)別? quitSafely方法效率比quit方法標(biāo)率低一點(diǎn),但是安全。具體選擇哪種就要看具體項(xiàng)目了。
總結(jié):
1.HandlerThread適用于構(gòu)建循環(huán)線程。
2.在創(chuàng)建Handler作為HandlerThread線程消息執(zhí)行者的時(shí)候必須調(diào)用start方法之后,因?yàn)閯?chuàng)建Handler需要的Looper參數(shù)是從HandlerThread類中獲得,而Looper對(duì)象的賦值又是在HandlerThread的run方法中創(chuàng)建。
相關(guān)文章
Android打開系統(tǒng)相機(jī)并拍照的2種顯示方法
這篇文章主要介紹了Android打開系統(tǒng)相機(jī)并拍照的2種顯示方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05Android自定義控件實(shí)現(xiàn)可多選課程日歷CalendarView
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)可多選課程日歷CalendarView,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05Android studio中生成引用.aar和.jar的方法詳解
這篇文章主要是講解.aar的生成與引用,文中的內(nèi)容屬于完全基礎(chǔ)性概念,對(duì)剛學(xué)習(xí)使用Android studio的朋友們很有幫助,有需要的可以參考學(xué)習(xí),下面來(lái)一起看看吧。2016-09-09Android中ListView的item點(diǎn)擊沒有反應(yīng)的解決方法
這篇文章主要介紹了Android中ListView的item點(diǎn)擊沒有反應(yīng)的相關(guān)資料,需要的朋友可以參考下2017-10-10大型項(xiàng)目里Flutter測(cè)試應(yīng)用實(shí)例集成測(cè)試深度使用詳解
這篇文章主要為大家介紹了大型項(xiàng)目里Flutter測(cè)試應(yīng)用實(shí)例集成測(cè)試深度使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Android自定義View實(shí)現(xiàn)粉碎的面具效果
這篇文章主要給大家介紹了關(guān)于Android自定義View實(shí)現(xiàn)粉碎的面具效果的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08Android編程實(shí)現(xiàn)通訊錄中聯(lián)系人的讀取,查詢,添加功能示例
這篇文章主要介紹了Android編程實(shí)現(xiàn)通訊錄中聯(lián)系人的讀取,查詢,添加功能,涉及Android權(quán)限控制及通訊錄相關(guān)操作技巧,需要的朋友可以參考下2017-07-07