本平臺的文章更新會有延遲,大家可以關注微信公眾號-顧林海,包括年底前會更新kotlin由淺入深系列教程,目前計劃在微信公眾號進行首發(fā),如果大家想獲取最新教程,請關注微信公眾號,謝謝
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。
頻繁的創(chuàng)建和銷毀線程是很耗資源的,因此推薦使用HandlerThread。
從上面代碼中可以看出HandlerThread繼承自Thread,那么HandlerThread就是一個線程類,并且內(nèi)部有自己的Looper對象,可以進行l(wèi)ooper循環(huán),我們通過獲取HandlerThread的Looper對象并將Looper對象傳遞給Handler對象,可以在HandleMessage方法中執(zhí)行異步任務。
HandlerThread的優(yōu)點是執(zhí)行任務時不會堵塞,減少了對性能的消耗,缺點是不能同時進行多個任務的執(zhí)行,因為是串行隊列,需要等待上一個任務執(zhí)行完成才能進行下一個任務的處理,處理效率較低。
內(nèi)部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方法中創(chuàng)建當前線程的Looper對象,并開啟消息隊列的循環(huán),synchronized同步代碼塊保證多個線程同時執(zhí)行這段代碼時,只有一個線程執(zhí)行,當Looper創(chuàng)建完畢后會調用notifyAll方法通知下面的getLooper方法不再處于阻塞狀態(tài)。
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高。

Android、Java、Python、Go、PHP、IOS、C++、HTML等等技術文章,更有各種書籍推薦和程序員資訊,快來加入我們吧!關注技術共享筆記。

定期推送優(yōu)質文章