概述
HandlerThread是Thread的子类,由HandlerThread创建的子线程可以直接创建Handler(由Thread直接创建的子线程必须要先创建Looper才能创建Handler);
构造方法
- HandlerThread(String name)
name:线程名称; - HandlerThread(String name, int priority)
priority:线程优先级,用于在run()方法中设置Process.setThreadPriority(priority),而不是直接给Thread设置优先级Thread.setPriority(priority);
成员变量
- int mPriority
线程优先级; - int mTid
线程ID,在run()方法中通过Process.myTid()获取; - Looper mLooper
当前线程的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;
}
首先调用Looper.prepare()创建Looper为线程初始化消息队列;
然后获取此Looper对象的引用,并调用onLooperPrepared();
最后调用Looper.loop()开始消息循环;
- onLooperPrepared()
用于给子类复写在消息循环之前做一些操作; - getLooper()
public Looper getLooper() {
if (!isAlive()) {
return null;
}
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
返回当前Thread的Looper对象,如果Thread的isAlive()方法返回为false,则直接返回null,如果线程已经start,则会阻塞等待Looper的初始化(如果mLooper为空,则会调用wait()等待,直到run()方法中Looper初始化完成会调用notifyAll()唤醒);
- quit()
调用Looper.quit()退出消息循环;
实例
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());
// 模拟耗时操作
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Toast.makeText(TestActivity.this, "耗时操作执行完成!", Toast.LENGTH_SHORT).show();
}
};
}
public void click(View v) {
mHandler.sendMessage(mHandler.obtainMessage());
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}
使用HandlerThread可以在子线程中直接创建Handler处理消息。