public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.post(r);
System.out.println("Activity----->"+Thread.currentThread().getId());
System.out.println("Activity----->"+Thread.currentThread().getName());
}
Runnable r=new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("Handler----->"+Thread.currentThread().getId());
System.out.println("Handler----->"+Thread.currentThread().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};谁能解释下上面代码的执行顺序,为什么是
先输出这两句
System.out.println("Activity----->"+Thread.currentThread().getId());
System.out.println("Activity----->"+Thread.currentThread().getName());
再是
System.out.println("Handler----->"+Thread.currentThread().getId());
System.out.println("Handler----->"+Thread.currentThread().getName());
最后隔了10秒,再
setContentView(R.layout.main);
在屏幕上输出这个视图
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.post(r);
System.out.println("Activity----->"+Thread.currentThread().getId());
System.out.println("Activity----->"+Thread.currentThread().getName());
}
Runnable r=new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("Handler----->"+Thread.currentThread().getId());
System.out.println("Handler----->"+Thread.currentThread().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};谁能解释下上面代码的执行顺序,为什么是
先输出这两句
System.out.println("Activity----->"+Thread.currentThread().getId());
System.out.println("Activity----->"+Thread.currentThread().getName());
再是
System.out.println("Handler----->"+Thread.currentThread().getId());
System.out.println("Handler----->"+Thread.currentThread().getName());
最后隔了10秒,再
setContentView(R.layout.main);
在屏幕上输出这个视图
可不可以这么理解
handler.post(r);
是把该线程加到队列的末尾
setContentView(R.layout.main);
没有马上显示视图,在onCreat方法结束的时候才显示?
而handler的runnable是需要主线程来启动的
view的显示在启动过程中是最后一部,可以理解成view的显示和activity完全独立的两部分。setContentView只是说我这个activity需要这个view,至于显示不是我activity管的事。
第二:setContentView只是告诉系统我会用到这个view来显示,至于真正在screen上绘制出来是在onCreate方法执行结束后的事情啦
至于为什么后输出线程里的东西,那就简单了,因为post是传入线程队列,
System.out.println("Activity----->"+Thread.currentThread().getId());
System.out.println("Activity----->"+Thread.currentThread().getName());执行完后,post里的r线程还没有开始执行,所以
System.out.println("Handler----->"+Thread.currentThread().getId());
System.out.println("Handler----->"+Thread.currentThread().getName());要后输出了