說起HandlerThread我的確沒怎么用到過卸察,以至于面試的時候被面試官問起時也是完全不知道。所以驱负,今天就來補一補這個東西嗦玖。其實這個類也不大,就149行代碼跃脊。下面就這英文看下意思宇挫,當然如果覺得英文煩躁,可以去掉英文就著我蹩腳的翻譯暫且看看:
/** 開啟一個帶有l(wèi)ooper的線程酪术,start()方法必須調用(開啟線程肯定得調用start()方法啊!)器瘪。
* 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;//優(yōu)先級
int mTid = -1;//獲取調用進程的線程ID
Looper mLooper;//Looper對象
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.
*/
//構造函數(shù):傳入一個String 對象做線程的名字,一個int值代表線程優(yōu)先級绘雁。
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.
*/
//可以重寫這個函數(shù)做一些準備工作橡疼,這個放方法在loop()方法調用之前調用。
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
//喚醒在等待的
notifyAll();
}
Process.setThreadPriority(mPriority);
//在loop()方法調用之前調用
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 {
//如果Looper未創(chuàng)建好庐舟,就先等待欣除,對應上面的notifyAll();
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
*/
//直接退出,調用了looper.quit()方法;
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.
*/
//安全退出挪略,調用了quitSafely()方法
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
//返回Process.myTid()
public int getThreadId() {
return mTid;
}
}
大體意思:
在一個線程中創(chuàng)建了一個Looper對象历帚,而我們知道Looper對象是消息機制的核心。那我們在子線程中弄這樣一個Looper對象就意味著該子線程也能像UI線程那樣瘟檩,通過Handle進行線程之間的切換工作抹缕,從某個線程切換到該子線程中來澈蟆。
那么墨辛,它到底有什么好處呢?
場景
我們來想一個場景趴俘,如果我們現(xiàn)在需要請求網(wǎng)絡數(shù)據(jù)(假設需要請求一張圖片睹簇,圖片請求返回后需要更新UI),我們都知道UI線程中不允許進行耗時的網(wǎng)絡請求寥闪。那么太惠,我們通常會開啟一個子線程來進行請求:如果你不用網(wǎng)絡請求的三方庫,一般會通過new Thread疲憋。然后start()來完成吧凿渊!這樣的話,如果有多次請求圖片缚柳,那么我們就得new 很多個Thread埃脏。所以這是個問題!G锩Α彩掐!
現(xiàn)在你就會想,難道(柯南BGM)你是說灰追。堵幽。狗超。沒錯,HandlerThread可以用來解決這個問題朴下。還有這種騷操作努咐?
問題解決分析
通過上面代碼我們知道:HandlerThread一個子線程,并且含有一個Looper殴胧。
再來看看那個問題:我們之所以需要new Thread麦撵。。然后start().是因為UI線程無法進行網(wǎng)絡請求溃肪,但是免胃,HandlerThread可是一個子線程。惫撰。羔沙。重要的說三遍。所以厨钻,在它里面可以直接請求網(wǎng)絡扼雏,于是上面的new Thread 。夯膀。 start()問題就解決了诗充。(臥槽。诱建。蝴蜓。這也是騷操作?)俺猿。
當然茎匠,就憑他是個子線程還沒法說服我,雖然它是一個子線程不需要new Thread()押袍,但是它自己也可能需要多次創(chuàng)建八忻啊!只不過是從new一個Thread變成了new HanderThread而已谊惭。這還不是沒卵用汽馋。(這這這。圈盔。豹芯。)
那么如何解釋它不需要重復創(chuàng)建呢?
其實也不難药磺,只需要子線程不結束不就行了告组。(run方法中加個while(true)啊,呵呵)癌佩,不過木缝,它這里并不是while(true),而是用到了調用了一個loop()方法便锨。
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//loop方法是阻塞的
Looper.loop();
mTid = -1;
}
loop方法是阻塞的,所以它后面的語句在它未退出的(可以通過quit()方法和quitSafely()方法退出)時候是沒辦法執(zhí)行的我碟。再加上它可以通過在外部實現(xiàn)一個Handler放案,然后,通過這個Handler給Looper發(fā)送message矫俺,近而源源不斷的實現(xiàn)網(wǎng)絡請求吱殉。所以,這就真正的解決了上面提出的那個問題厘托。(我墻都不服友雳。。铅匹。)
這里給一個連接押赊,里面介紹了如何在外部創(chuàng)建一個Handler,然后源源不斷進行網(wǎng)絡請求。
鏈接地址:Android 多線程之HandlerThread 完全詳解
總結一下優(yōu)缺點:
引用一篇文章:
作者:Cooke_
鏈接:http://www.reibang.com/p/e9b2c0831b0d
來源:簡書
- HandlerThread將loop轉到子線程中處理包斑,說白了就是將分擔MainLooper的工作量流礁,降低了主線程的壓力,使主界面更流暢罗丰。
- 開啟一個線程起到多個線程的作用神帅。處理任務是串行執(zhí)行,按消息發(fā)送順序進行處理萌抵。
- 相比多次使用new Thread(){…}.start()這樣的方式節(jié)省系統(tǒng)資源找御。
- 但是由于每一個任務都將以隊列的方式逐個被執(zhí)行到,一旦隊列中有某個任務執(zhí)行時間過長谜嫉,那么就會導致后續(xù)的任務都會被延遲處理萎坷。
- HandlerThread擁有自己的消息隊列凹联,它不會干擾或阻塞UI線程沐兰。
- 通過設置優(yōu)先級就可以同步工作順序的執(zhí)行,而又不影響UI的初始化蔽挠;