在我们默认的利用post方法将线程添加到handler消息队列中时,其实此时并不是调用了线程的start方法,而是直接调用了线程的run方法,那么也就是说,他并没有在新线程中运行,为了证实这一结论,用一个简单的小程序来看一下:
- package cn.android.handler;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.util.Log;
- public class Handlertest extends Activity{
- private static final String SWORD="SWORD";
- private Handler handler = new Handler();
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //将线程r添加到handler的消息队列
- handler.post(r);
- //日志输出此线程的id与name
- Log.i(SWORD,"activityId-->"+Thread.currentThread().getId());
- Log.i(SWORD,"activityName-->"+Thread.currentThread().getName());
- }
- Runnable r = new Runnable(){
- public void run(){
- //日志输出该线程的id和name
- Log.i(SWORD,"handlerId-->"+Thread.currentThread().getId());
- Log.i(SWORD,"handlerName-->"+Thread.currentThread().getName());
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- }