Android小知識-什麼是HandlerThread
public class HandlerThread extends Thread { int mPriority; int mTid = -1; Looper mLooper; private @Nullable Handler mHandler; public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } public HandlerThread(String name, int priority) { super(name); mPriority = priority; } 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; } 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; } @NonNull public Handler getThreadHandler() { if (mHandler == null) { mHandler = new Handler(getLooper()); } return mHandler; } 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; } public int getThreadId() { return mTid; } }
一言不合貼程式碼還請海涵,幸好程式碼不多。
什麼是HandlerThread,簡單粗暴來講就是Handler+Thread+Looper。
頻繁的建立和銷燬執行緒是很耗資源的,因此推薦使用HandlerThread。
從上面程式碼中可以看出HandlerThread繼承自Thread,那麼HandlerThread就是一個執行緒類,並且內部有自己的Looper物件,可以進行looper迴圈,我們通過獲取HandlerThread的Looper物件並將Looper物件傳遞給Handler物件,可以在HandleMessage方法中執行非同步任務。
HandlerThread的優點是執行任務時不會堵塞,減少了對效能的消耗,缺點是不能同時進行多個任務的執行,因為是序列佇列,需要等待上一個任務執行完成才能進行下一個任務的處理,處理效率較低。
內部run方法:
public class HandlerThread extends Thread { @Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } 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; } }
在run方法中建立當前執行緒的Looper物件,並開啟訊息佇列的迴圈,synchronized同步程式碼塊保證多個執行緒同時執行這段程式碼時,只有一個執行緒執行,當Looper建立完畢後會呼叫notifyAll方法通知下面的getLooper方法不再處於阻塞狀態。
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; }
quit和quitSafely方法都是使looper退出當前執行緒,quitSafely方法更安全但效率上沒有quit高。

掃碼_搜尋聯合傳播樣式-標準色版.png
Android、Java、Python、Go、PHP、IOS、C++、HTML等等技術文章,更有各種書籍推薦和程式員資訊,快來加入我們吧!關注技術共享筆記。

838794-506ddad529df4cd4.webp.jpg
定期推送優質文章