5.4.4 HandlerThread介绍

HandlerThread完美地解决了myLooper可能为空的问题。下面来看看它是怎么做的,代码如下所示:


[—>HandlerThread]

public class HandlerThread extends Thread{

//线程1调用getLooper来获得新线程的Looper

public Looper getLooper(){

……

synchronized(this){

while(isAlive()&&mLooper==null){

try{

wait();//如果新线程还未创建Looper,则等待

}catch(InterruptedException e){

}

}

}

return mLooper;

}

//线程2运行它的run函数,looper就是在run线程里创建的。

public void run(){

mTid=Process.myTid();

Looper.prepare();//创建这个线程上的Looper

synchronized(this){

mLooper=Looper.myLooper();

notifyAll();//通知取Looper的线程1,此时Looper已经创建好了。

}

Process.setThreadPriority(mPriority);

onLooperPrepared();

Looper.loop();

mTid=-1;

}

}


HandlerThread很简单,小小的wait/notifyAll就解决了我们的难题。为了避免重复发明轮子,我们还是多用HandlerThread类吧!