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