标签:proc link notifyall read -- get shared 简单 strong
一.简介
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,其他线程可以获取它来进行通信
三.具体实现
标签:proc link notifyall read -- get shared 简单 strong
原文地址:https://www.cnblogs.com/xiongbo753/p/9810057.html