🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
HandlerThread完美地解决了myLooper可能为空的问题。来看看它是怎么做的。代码如下所示: **HandlerThread** ~~~ public class HandlerThread extends Thread{ //线程1调用getLooper来获得新线程的Looper publicLooper getLooper() { ...... synchronized (this) { while (isAlive() && mLooper == null) { try { wait();//如果新线程还未创建Looper,则等待 } catch (InterruptedException e) { } } } return mLooper; } //线程2运行它的run函数,looper就是在run线程里创建的。 publicvoid 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类吧!