进来编写了一个小程序,想测试一下消息队列中语句的输出顺序,及实现的Runnable接口r是否和activity这个线程在同一个线程内,结果为:
(1)activityId->
(2)activityName->
(3)threadId->
(4)threadName->
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
public class HandlerTest2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.post(r);
System.out.println("(1)activityid-->"+Thread.currentThread().getId());
System.out.println("(2)activityid-->"+Thread.currentThread().getName());
}
Handler handler = new Handler();
Runnable r= new Runnable(){
public void run() {
System.out.println("(3)threadId->"+Thread.currentThread().getId());
System.out.println("(4)threadName->"Thread.currentThread().getName());
}
};
}
为什么不是:
(3)threadId->
(4)threadName->
(1)activityId->
(2)activityName->
按照程序的执行顺序,先执行handler.post(r);
调用的是r对象中的run()先输出(3)(4)才对啊 。。怎么先输出(1)(2)啊?????????
请高手赐教。。。。
------解决方案--------------------
post是把Runnable压倒消息队列中,主线程还是继续向下执行的,而同时Looper在不断地向消息队列取消息,
这样情况,因为1和2的输出在Looper取出消息之前就完成了。
------解决方案--------------------
System.out.println 不属于UI线程,实时打印
而handler需要等activity初始化完成后才会运行。
------解决方案--------------------
android里面主线程先于子线程执行,子线程要等主线程执行完后,才能执行