- 作用 :獲取子線程的looper,使用該looper初始化handler時可以獲取子線程的handler對象
- 用法
- HandlerThread mHanderThread = new HandlerThread("threadName");
- mHanderThread.start();//獲取位於新線程的Looper對象
- Handler mHander = new Hander(mHandlerThread.getLooper());//至此創建了一個子線程處理任務的Handler對象,可以在此mHandler中處理耗時任務
- HandlerThread方法裏面最後退出釋放資源有兩個方法,分別是quit()和quitSafely(),下面看一下這兩個方法的區別:由HandlerThread源碼可知這兩個方法最終分別調用了MessageQueue裏面的以下兩個方法
private void removeAllMessagesLocked() { Message p = mMessages; while (p != null) { Message n = p.next; p.recycleUnchecked(); p = n; } mMessages = null; }
private void removeAllFutureMessagesLocked() { final long now = SystemClock.uptimeMillis(); Message p = mMessages; if (p != null) { if (p.when > now) { removeAllMessagesLocked(); } else { Message n; for (;;) { n = p.next; if (n == null) { return; } if (n.when > now) { break; } p = n; } p.next = null; do { p = n; n = p.next; p.recycleUnchecked(); } while (n != null); } } }
最終到了MessageQueue的removeAllMessageLocked()和removeAllFutureMessageLocked(),由上面的代碼可知,前一個方法刪除了所有messageQueue裏面的message,後面一個判斷了時間,只刪除了執行時間大於當前時間的message,也就是說會把delay爲0以及當前需要執行的message執行完。 - 總結:
HandlerTheard繼承自 Thread類,並創建位於該線程的Looper對象,提供了getLooper()方法來獲取創建的looper對象,以及quit()和quitSafely()兩個方法退出並釋放messageQueue隊列 ,注意run()方法裏面的notifyAll和getLooper方法裏面的wait。解決了多線程操作的線程同步問題,因爲getLooper是在一個線程調用而run方法是在另一個線程調用,getLooper方法執行時如果run方法沒有執行則進入wait等待,直到run方法中looper初始化完畢喚醒該方法。
HandlerThread詳解
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.