定义类的代码:
public class HandlerThread extends Thread { public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } /** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * @return The looper. */ 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) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
HandlerThread继承于Thread,是一个线程类。它实现了run方法,我们可以直接调用start方法来运行这个线程。 和我们使用线程的传统方式不一样的是:传统方法中,我们一般是在run方法中做我们实际想做的事情。而HandlerThread已经实现了run方法,不需要我们实现,它在run方法里面启动了一个looper循环,使得HandlerThread具有了处理消息的能力,同时提供了安全的getLooper方法(之所以安全,是因为getLooper使用了wait/notify机制),getLooper()方法使得app可以创建指定Looper的Handler,通过这个Handler我们就可以使用发送消息的方法通知线程做指定的事情。
使用例子如下:
Thread mThread = new HandlerThread("demo", Process.THREAD_PRIORITY_BACKGROUND); mThread.start() //启动线程,这时run方法会为这个Thread创建消息循环,消息循环是一个死循环,所以这个Thread会一直处于运行状态 MyHandler mHandler = new MyHandler( mThread.getLooper( ) ) //使用mThread的looper来实例化一个自定义的Handler
这样我们就得到了一个mHandler的实例,使用mHandler.sendMessage(msg) 就可以让mThread 做指定的事情了(指定的事情是通过msg来区分的),而指定的事情是在 MyHandler的handlerMessage中实现的。
实例代码如下(这个大家应该很熟悉):
class MyHandler extends Handler { @Override public void handlerMessage(Message msg) { //在这里实现线程需要做的事情(传统的线程使用方式中,我们是在run方法里面实现线程需要做的事情) } }
总结:
HandlerThread和传统Thread不同,它有一个消息循环,这个消息循环由run方法来承担,run方法不做任何实际需求的事情,这样使得线程的可控性得到了增强,我们可以通过发送不同的消息让线程做不同的事情。