hanlder.post(new Runnable() {
public void run() {
for(int i=0; i<10; i++){
// 发送msg后不会立即执行handlerMessage方法,由于handler是同步的,所以在run结束后才执行
hanlder.sendEmptyMessage(0);
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("handler_send_msg"+i);
}
}
});
private Handler hanlder = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
pd.incrementProgressBy(5);
Toast.makeText(context, "hello world", -1).show();
System.out.println("handler_send_msg");
}
};
console 打印出来的信息是:
08-07 03:19:30.310: INFO/System.out(22937): handler_send_msg0
08-07 03:19:32.326: INFO/System.out(22937): handler_send_msg1
08-07 03:19:34.377: INFO/System.out(22937): handler_send_msg2
08-07 03:19:36.398: INFO/System.out(22937): handler_send_msg3
08-07 03:19:38.487: INFO/System.out(22937): handler_send_msg4
08-07 03:19:40.517: INFO/System.out(22937): handler_send_msg5
08-07 03:19:42.578: INFO/System.out(22937): handler_send_msg6
08-07 03:19:44.608: INFO/System.out(22937): handler_send_msg7
08-07 03:19:46.626: INFO/System.out(22937): handler_send_msg8
08-07 03:19:48.679: INFO/System.out(22937): handler_send_msg9
08-07 03:19:49.167: INFO/System.out(22937): handler_send_msg
08-07 03:19:49.407: INFO/System.out(22937): handler_send_msg
08-07 03:19:49.647: INFO/System.out(22937): handler_send_msg
08-07 03:19:49.807: INFO/System.out(22937): handler_send_msg
08-07 03:19:49.947: INFO/System.out(22937): handler_send_msg
08-07 03:19:49.987: INFO/System.out(22937): handler_send_msg
08-07 03:19:50.037: INFO/System.out(22937): handler_send_msg
08-07 03:19:50.087: INFO/System.out(22937): handler_send_msg
08-07 03:19:50.137: INFO/System.out(22937): handler_send_msg
08-07 03:19:50.177: INFO/System.out(22937): handler_send_msg
由 System.out(22937): 可以看到是同一个线程