Android开发之handler(三)handler真的是重新启动一个线程吗?

         在handler(二)中点击打开链接,我们说handler是开启了另外一个线程,而且看代码的话确实是这样,实现了runnable接口,这在java中就是开启了一个线程,但是情况中的是这样吗?我们不妨来做个试验,如下

 

package com.handlerThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;

public class handlerThread extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Handler handler = new Handler();
        handler.post(r);
        System.out.println("activity线程ID:"+Thread.currentThread().getId());
        System.out.println("activity线程name:"+Thread.currentThread().getName());
    }
    
    Runnable r = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
	        System.out.println("handler线程ID:"+Thread.currentThread().getId());
	        System.out.println("handler线程name:"+Thread.currentThread().getName());
	        try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    	
    };
}
运行结果

其实,当我看到这里的时候也不敢相信,但是事实就是这样,handler没有重新开启一个线程,而是跟activity在同一个线程里,但是这种写法也就非常接近java的标准线程的写法了,难怪会误导人,如下是java的标准线程写法。

package com.handlerThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;

public class handlerThread extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
//        Handler handler = new Handler();
//        handler.post(r);
        Thread t = new Thread(r);
        t.start();
        System.out.println("activity线程ID:"+Thread.currentThread().getId());
        System.out.println("activity线程name:"+Thread.currentThread().getName());
    }
    
    Runnable r = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
	        System.out.println("handler线程ID:"+Thread.currentThread().getId());
	        System.out.println("handler线程name:"+Thread.currentThread().getName());
	        try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    	
    };
}
运行结果如下:

这里就才是我们这种想要的结果,两者比较我们就会发现,handler虽然实现了runnable接口,但是却并没有启动一个线程,而是直接调用run方法。那andriod为什么要这样设计呢,既然不启动新的线程,为什么还要多此一举来实现runnable接口呢,我们继续探讨,下次再说。

你可能感兴趣的:(Android)