HandlerThread

  1. 正常情況下使用線程我們都是直接new Thread.start來開啟,但是這種方式是執(zhí)行完run 方法后線程結(jié)束了,當(dāng)我們有多個(gè)線程的時(shí)候意味著我們需要開啟多個(gè)線程去執(zhí)行,這樣是很耗費(fèi)CPU資源的。

  2. HandlerThread解決了這個(gè)問題,它是一個(gè)繼承于Thread的類,內(nèi)部的run方法實(shí)現(xiàn)了一套looper機(jī)制,可以不讓這個(gè)子線程結(jié)束。內(nèi)部的looper里面有一個(gè)死循環(huán),如果有消息就把任務(wù)發(fā)送到子線程中處理,沒有則掛起等待新的消息到來。

使用場景
如果你有多個(gè)耗時(shí)操作需要開啟多個(gè)子線程操作的話,你可以考慮使用它,它的好處是一個(gè)線程可以持續(xù)的執(zhí)行多個(gè)任務(wù)隊(duì)列,節(jié)省資源方便維護(hù)。 壞處是不適合那些需要馬上響應(yīng)的耗時(shí)操作,比如網(wǎng)絡(luò)請求,如果網(wǎng)絡(luò)請求走隊(duì)列的話,任務(wù)一多請求就會一直堵塞等待執(zhí)行。

注意事項(xiàng)
Handler如果要在子線程中創(chuàng)建必須調(diào)用 Looper.prepare();初始化一個(gè)looper,Handler會在構(gòu)造檢查looper沒有會拋出異常,但是在主線程中就不需要,因?yàn)橹骶€程中默認(rèn)已經(jīng)包含了一個(gè)MainLooper對象。

檢查Looper的代碼


 mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()"); 
        }

使用起來

HandlerThread handlerThread = new HandlerThread("mainhander");
        handlerThread.start();
        Handler handler = new Handler(handlerThread.myLooper()) {

            @Override
            public void dispatchMessage(Message msg) {
                LogU.Log("pId=" + Process.myTid());
            }
        };
        handler.sendEmptyMessage(1);

這個(gè)時(shí)候handlerThread子線程已經(jīng)具備了隊(duì)列的功能,而且線程是一直在的,內(nèi)部的Looper一直處理掛起狀態(tài)等帶新的消息到來。

結(jié)束handlerThread線程

handlerThread自帶了二個(gè)結(jié)束線程隊(duì)列的方法, 一個(gè)是線程安全一個(gè)線程不安全,當(dāng)我們不需要在用這個(gè)子線程的時(shí)候需要及時(shí)的結(jié)束它,免的占用資源。

 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;
    }

Looper初始化特點(diǎn)
1.子線程的Looper就變成子線程回調(diào)
2.主線程的Looper就變成主線程回調(diào)

/**
 * 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;
    int mTid = -1;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    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();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

    /**
     * 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() {
        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;
    }

    /**
     * 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;
    }

    /**
     * Quits the handler thread's looper safely.
     * <p>
     * Causes the handler thread's looper to terminate as soon as all remaining messages
     * in the message queue that are already due to be delivered have been handled.
     * Pending delayed messages with due times in the future will not be delivered.
     * </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>
     * If the thread has not been started or has finished (that is if
     * {@link #getLooper} returns null), then false is returned.
     * Otherwise the looper is asked to quit and true is returned.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     */
    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;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 【Android Handler 消息機(jī)制】 前言 在Android開發(fā)中,我們都知道不能在主線程中執(zhí)行耗時(shí)的任務(wù)...
    Rtia閱讀 5,091評論 1 28
  • 一.HandlerThread的使用與原理解析 ??HandlerThread繼承于Thread,所以它本質(zhì)就是個(gè)...
    Geeks_Liu閱讀 2,218評論 1 26
  • 第5章 多線程編程 5.1 線程基礎(chǔ) 5.1.1 如何創(chuàng)建線程 在java要?jiǎng)?chuàng)建線程,一般有==兩種方式==:1)...
    AndroidMaster閱讀 1,921評論 0 11
  • 我從不否認(rèn)楊過是個(gè)大俠,對他跟小龍女的愛情也深為感動(dòng),對他辜負(fù)公孫綠萼程英陸無雙的感情也報(bào)以理解,但他有一件事做的...
    一夕厘閱讀 433評論 2 2
  • Guru有大師的意思,而Glue是膠水/漿糊。聽上去發(fā)音有點(diǎn)類似,而在上海話中, “漿糊”有“糊弄、敷衍”等意思...
    可的視界閱讀 637評論 3 3

友情鏈接更多精彩內(nèi)容