HandlerThread的简单分析
Posted xiongbo753
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HandlerThread的简单分析相关的知识,希望对你有一定的参考价值。
一.简介
HanlerThread就是一个封装了Loop的Thread,其他线程能够通过创建Handler传进去该Looper,与HandlerThread通信
二.源码分析
1.因为其是一个Thread,所以可以从run方法看起
@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
该代码就是创建一个Looper,onLooperPrepared() ---是Looper实现之前的准备工作,我们可以重写它来实现自己的逻辑
2.getLooper() 方法
/** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason 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; }
该代码表明,如果需要获取到Looper,那么Thread一定需要先启动。
3.getThreadHandler()
/** * @return a shared {@link Handler} associated with this thread * @hide */ @NonNull public Handler getThreadHandler() { if (mHandler == null) { mHandler = new Handler(getLooper()); } return mHandler; }
该方法主要是获取用 mLooper创建的Handler,其他线程可以获取它来进行通信
三.具体实现
以上是关于HandlerThread的简单分析的主要内容,如果未能解决你的问题,请参考以下文章
从HandlerThread 的使用来分析HandlerThread的源码