题主的问题如下:
向大家请教一下哈~一个handler到底对应几个队列?是只有消息队列,还是对应线程(runnable)队列和消息队列这两个队列?调用post方法会向消息队列发送消息么?
还有下面这一段代码里为什么只在runnable接口的run方法里post(runnable)就不会再继续执行下一次run方法的执行呢?而且如果在run方法里不调用post方法,仅仅只在handleMessage方法里调用post方法也就只会执行一次run方法,不会继续再执行一次run方法(在程序运行的开始就先调用了一次post方法的)?
相关代码:
HandlerThread handlerThread = new HandlerThread("NEW_THREAD");
handlerThread.start();
mainHandler = new MainHandler(getMainLooper());
childHandler = new ChildHandler(handlerThread.getLooper());
childHandler.post(runnable);
Log.d("TAG","AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("TAG","RunRunRunRunRunRunRunRunRunRunRunRun~~~~~~~~~~~Thread---" + Thread.currentThread().getName());
Log.i("TAG","SleepSleepSleepSleepSleep");
childHandler.postDelayed(runnable, 3000);//这边不加这一句就只在handleMessage里post,就只会执行一次run方法
}
};
}
class ChildHandler extends Handler {
public ChildHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.i("TAG", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC---handleMessage----THREAD===" + Thread.currentThread().getName() + msg);
childHandler.postDelayed(runnable, 3000);//如果这边没有这一句就只有run方法里post,那一次run方法都不会执行
}
}
找到的bug:
childHandler.post(runnable); 该句代码中的runnable此时并没有被创建,为null,因此调用的是handle message方法,也就是如果handlemessage方法中没有post的话一次run方法都不会执行。而handlemessage中的post执行时,runnable已经被创建了,因此,调用的是runnable的run方法,也就是如果runnable的run方法中没有post的话,就只会执行一次run方法。