概述
HandlerThread是Thread的子類,由HandlerThread創(chuàng)建的子線程可以直接創(chuàng)建Handler(由Thread直接創(chuàng)建的子線程必須要先創(chuàng)建Looper才能創(chuàng)建Handler)像街;
構(gòu)造方法
- HandlerThread(String name)
name:線程名稱淡诗; - HandlerThread(String name, int priority)
priority:線程優(yōu)先級,用于在run()方法中設(shè)置Process.setThreadPriority(priority)肤频,而不是直接給Thread設(shè)置優(yōu)先級Thread.setPriority(priority);
成員變量
- int mPriority
線程優(yōu)先級; - int mTid
線程ID梗顺,在run()方法中通過Process.myTid()獲取车摄; - Looper mLooper
當(dāng)前線程的Looper對象寺谤;
成員方法
- run()
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
首先調(diào)用Looper.prepare()創(chuàng)建Looper為線程初始化消息隊(duì)列仑鸥;
然后獲取此Looper對象的引用,并調(diào)用onLooperPrepared()变屁;
最后調(diào)用Looper.loop()開始消息循環(huán)眼俊;
- onLooperPrepared()
用于給子類復(fù)寫在消息循環(huán)之前做一些操作; - getLooper()
public Looper getLooper() {
if (!isAlive()) {
return null;
}
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
返回當(dāng)前Thread的Looper對象粟关,如果Thread的isAlive()方法返回為false疮胖,則直接返回null,如果線程已經(jīng)start闷板,則會阻塞等待Looper的初始化(如果mLooper為空澎灸,則會調(diào)用wait()等待,直到run()方法中Looper初始化完成會調(diào)用notifyAll()喚醒)蛔垢;
- quit()
調(diào)用Looper.quit()退出消息循環(huán)击孩;
實(shí)例
public class TestActivity extends Activity {
public static final String TAG = "Lee";
private HandlerThread mHandlerThread;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mHandlerThread = new HandlerThread("test");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, Thread.currentThread().toString());
// 模擬耗時(shí)操作
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Toast.makeText(TestActivity.this, "耗時(shí)操作執(zhí)行完成!", Toast.LENGTH_SHORT).show();
}
};
}
public void click(View v) {
mHandler.sendMessage(mHandler.obtainMessage());
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}
使用HandlerThread可以在子線程中直接創(chuàng)建Handler處理消息鹏漆。