標籤:call 資源 調用 click mod led 結束 isa oci
HandlerThread 簡單介紹:
我們知道Thread線程是一次性消費品,當Thread線程運行完一個耗時的任務之後。線程就會被自己主動銷毀了。假設此時我又有一
個耗時任務須要運行,我們不得不又一次建立線程去運行該耗時任務。然而。這樣就存在一個效能問題:多次建立和銷毀線程是非常耗
系統資源的。為瞭解這樣的問題,我們能夠自己構建一個迴圈線程Looper Thread。當有耗時任務投放到該迴圈線程中時。線程運行耗
時任務,運行完之後迴圈線程處於等待狀態,直到下一個新的耗時任務被投放進來。這樣一來就避免了多次建立Thread線程導致的
效能問題了。或許你能夠自己去構建一個迴圈線程,但我能夠告訴你一個好訊息。Aandroid SDK中事實上已經有一個迴圈線程的架構
了。此時你僅僅須要掌握其怎麼使用的就ok啦!當然就是我們今天的主角HandlerThread啦!
接下來請HandlerThread上場,鼓掌~~
HandlerThread的父類是Thread,因此HandlerThread事實上是一個線程,僅僅只是其內部幫你實現了一個Looper的迴圈而已。
那麼我們
先來瞭解一下Handler是怎麼使用的吧。
【轉載請註明出處:Android HandlerThread 原始碼分析 CSDN 廢墟的樹】
HandlerThread使用步驟:1.建立執行個體對象
HandlerThread handlerThread = new HandlerThread("handlerThread");
以上參數能夠隨意字串。參數的作用主要是標記當前線程的名字。
2.啟動HandlerThread線程
handlerThread.start();
到此,我們就構建完一個迴圈線程了。
那麼你可能會懷疑。那我怎麼將一個耗時的非同步任務投放到HandlerThread線程中去運行呢?當然是有辦法的,接下來看第三部。
3.構建迴圈訊息處理機制
Handler subHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { //實現自己的訊息處理 return true; } });
第三步建立一個Handler對象。將上面HandlerThread中的looper對象最為Handler的參數。然後重寫Handler的Callback介面類中的
handlerMessage方法來處理耗時任務。
總結:以上三步順序不能亂,必須嚴格依照步驟來。到此,我們就能夠調用subHandler以發送訊息的形式發送耗時任務到線程
HandlerThread中去運行。言外之意就是subHandler中Callback介面類中的handlerMessage方法事實上是在背景工作執行緒中啟動並執行。
HandlerThread執行個體:
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() { //該介面的實現就是處理非同步耗時任務的,因此該方法運行在子線程中 @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) { //投放非同步耗時任務到HandlerThread中 mSubHandler.sendEmptyMessage(0); } }); }}
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; //當前線程id int mTid = -1; //當前線程持有的Looper對象 Looper mLooper; //構造方法 public HandlerThread(String name) { //調用父類預設的方法建立線程 super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } //帶優先順序參數的構造方法 public HandlerThread(String name, int priority) { super(name); mPriority = priority; }...............}
分析:該類開頭就給出了一個描寫敘述:該類用於建立一個帶Looper迴圈的線程,Looper對象用於建立Handler對象,值得注意的是在建立Handler
對象之前須要調用start()方法啟動線程。
這裡可能有些人會有疑問?為啥須要先調用start()方法之後才幹建立Handler呢?後面我們會解答。
上面的代碼凝視已經非常清楚了。HandlerThread類有兩個構造方法。不同之處就是設定當前線程的優先順序參數。你能夠依據自己的情況來設定優先
級,也能夠使用預設優先順序。
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() { //獲得當前線程的id mTid = Process.myTid(); //準備迴圈條件 Looper.prepare(); //持有鎖機制來獲得當前線程的Looper對象 synchronized (this) { mLooper = Looper.myLooper(); //發出通知,當前線程已經建立mLooper對象成功。這裡主要是通知getLooper方法中的wait notifyAll(); } //設定當前線程的優先順序 Process.setThreadPriority(mPriority); //該方法實現體是空的,子類能夠實現該方法,作用就是線上程迴圈之前做一些準備工作。當然子類也能夠不實現。 onLooperPrepared(); //啟動loop Looper.loop(); mTid = -1; }}
分析:以上代碼中的凝視已經寫得非常清楚了,以上run方法主要作用就是調用了Looper.prepare和Looper.loop構建了一個迴圈線程。
值得一提的
是。run方法中在啟動loop迴圈之前調用了onLooperPrepared方法,該方法的實現是一個空的。使用者能夠在子類中實現該方法。該方法的作用是
線上程loop之前做一些初始化工作,當然你也能夠不實現該方法,詳細看需求。
由此也能夠看出,Googleproject師在編寫代碼時也考慮到代碼的可擴充性。牛B!
HandlerThread的其它方法getLooper獲得當前線程的Looper對象
/** * 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. //假設線程已經啟動,可是Looper還未建立的話,就等待,知道Looper建立成功 synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
分析:事實上方法開頭的英文凝視已經解釋的非常清楚了:該方法主要作用是獲得當前HandlerThread線程中的mLooper對象。
首先推斷當前線程是否存活,假設不是存活的,這直接返回null。
其次假設當前線程存活的。在推斷線程的成員變數mLooper是否為null。假設為
null,說明當前線程已經建立成功,可是還沒來得及建立Looper對象,因此,這裡會調用wait方法去等待。當run方法中的notifyAll方法調用之後
通知當前線程的wait方法等待結束,跳出迴圈。獲得mLooper對象的值。
總結:在獲得mLooper對象的時候存在一個同步的問題。僅僅有當線程建立成功而且Looper對象也建立成功之後才幹獲得mLooper的值。這裡等待方法wait和run方法中的notifyAll方法共同完畢同步問題。
quit結束當前線程的迴圈
/** * 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; }//安全退出迴圈 public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }
分析:以上有兩種讓當前線程退出迴圈的方法,一種是安全的,一中是不安全的。
至於兩者有什麼差別? quitSafely方法效率比quit方法標率低一點。可是安全。詳細選擇哪種就要看詳細項目了。
總結:
1.HandlerThread適用於構建迴圈線程。
2.在建立Handler作為HandlerThread線程訊息運行者的時候必須調用start方法之後。由於建立Handler須要的Looper參數是從HandlerThread類中獲得,而Looper對象的賦值又是在HandlerThread的run方法中建立。
3.關於HandlerThread和Service的結合使用請參考還有一篇部落格:Android IntentService 原始碼分析
【轉載請註明出處:Android HandlerThread 原始碼分析 CSDN 廢墟的樹】
Android HandlerThread 原始碼分析