国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android實例HandlerThread源碼分析

2019-10-22 18:19:33
字體:
來源:轉載
供稿:網友

HandlerThread 簡介:
我們知道Thread線程是一次性消費品,當Thread線程執行完一個耗時的任務之后,線程就會被自動銷毀了。如果此時我又有一

個耗時任務需要執行,我們不得不重新創建線程去執行該耗時任務。然而,這樣就存在一個性能問題:多次創建和銷毀線程是很耗

系統資源的。為了解這種問題,我們可以自己構建一個循環線程Looper Thread,當有耗時任務投放到該循環線程中時,線程執行耗

時任務,執行完之后循環線程處于等待狀態,直到下一個新的耗時任務被投放進來。這樣一來就避免了多次創建Thread線程導致的

性能問題了。也許你可以自己去構建一個循環線程,但我可以告訴你一個好消息,Aandroid SDK中其實已經有一個循環線程的框架

了。此時你只需要掌握其怎么使用的就ok啦!當然就是我們今天的主角HandlerThread啦!接下來請HandlerThread上場,鼓掌~~

HandlerThread的父類是Thread,因此HandlerThread其實是一個線程,只不過其內部幫你實現了一個Looper的循環而已。那么我們

先來了解一下Handler是怎么使用的吧!

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之前做一些初始化工作,當然你也可以不實現該方法,具體看需求。由此也可以看出,Google工程師在編寫代碼時也考慮到代碼的可擴展性。牛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方法中創建。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沁源县| 大连市| 杨浦区| 博爱县| 清河县| 措美县| 克什克腾旗| 凯里市| 岐山县| 缙云县| 资兴市| 襄樊市| 马龙县| 新竹县| 揭西县| 松滋市| 同江市| 汝州市| 繁昌县| 阿坝县| 怀远县| 峨眉山市| 宜黄县| 中宁县| 信阳市| 东乡县| 咸宁市| 县级市| 大石桥市| 桃园县| 大城县| 泽州县| 高雄县| 大悟县| 永嘉县| 翁源县| 赤壁市| 竹山县| 高青县| 湖南省| 资兴市|