码迷,mamicode.com
首页 > 移动开发 > 详细

Android-HandlerThread

时间:2015-05-13 12:54:05      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:threadhandler

先看一个使用HandlerThread的例子:

public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		HandlerThread thread = new HandlerThread("handler_thread");//1 创建一个HandlerThread
		thread.start();

		final Handler handler = new Handler(thread.getLooper()) {//2 创建Handler的时候,使用HandlerThread的Looper
			@Override
			public void handleMessage(Message msg) {
				Log.i(TAG, msg.what+ ","+ Thread.currentThread().getName()); //4 在子线程中处理消息
				super.handleMessage(msg);
			}
		};

		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int j = 0; j < 5; j++) {
					Message msg = Message.obtain();
					msg.what = j;
					handler.sendMessage(msg);   //3 向handler发送消息
					try{Thread.sleep(1000);}catch(Exception e){}
				}
			}
		}).start();
	}

可以看出来,ThreadHandler提供了一种在非主线程中利用handler和looper的方式。

我们看下ThreadHandler的源码:

public class HandlerThread extends Thread { //继承了Thread
    ......
    Looper mLooper; //有一个Looper的成员变量
    ......
    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();   //在子线程中创建Looper
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();             //唤醒getLooper时等待的线程
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();              //开始消息循环
        mTid = -1;
    }
    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {  //这里保证Looper已经初始化完成
                try {
                    wait();                    
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }
}

ThreadHandler继承了Thread,在里面会创建Looper,开启消息循环,发送消息,使用ThreadHandler的Looper的Handler可以在子线程中进行消息处理。很明显,这比我们自己实现一种异步任务处理机制要简单的多得多。

Android-HandlerThread

标签:threadhandler

原文地址:http://blog.csdn.net/goldenfish1919/article/details/45690501

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!