一般情况下在子线程中创建Handler如下:
Handler handler; //创建全局变量
Thread mThread = new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "处理事件", Toast.LENGTH_LONG).show();
}
};
Looper.loop();
};
});
mThread.start();
//通过handler即可进行消息发送
handler.sendEmptyMessage(0);
通过handlerThread创建子线程与handler:
Handler mHandler;//创建全局变量
HandlerThread mHandlerThread = new HandlerThread("thread_name");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg)
{
Toast.makeText(getApplicationContext(), "HandlerThread 处理事件", Toast.LENGTH_LONG).show();
}
};
////通过mHandler即可进行消息发送
mHandler.sendEmptyMessage(0);
二者都是通过创建开启一个子线程来处理耗时操作,但是通过HandlerThread开启一个线程起到多个线程的作用。处理任务是串行执行,按消息发送顺序进行处理。
HandlerThread本质是一个线程,在线程内部,代码是串行处理的。但是由于每一个任务都将以队列的方式逐个被执行到,一旦队列中有某个任务执行时间过长,那么就会导致后续的任务都会被延迟处理。HandlerThread拥有自己的消息队列,它不会干扰或阻塞UI线程。
查看HandlerThread的源码:
创建Looper是在子线程的run方法中,但是我们在new Handler(mHandlerThread.getLooper())时调用getLooper()是在主线程中,为了解决线程不同步问题,HandlerThread内部则通过等待唤醒机制解决了此问题,关键代码如下:
run方法中:
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();//唤醒等待线程
}
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;
}
子线程handler与handlerThread
最新推荐文章于 2025-05-21 07:29:17 发布