Handler源码解析
Handler源码解析
一、基本原理回顾
在android开发中,经常会在子线程中进行一些操作,当操作完毕后会通过handler发送一些数据给主线程,通知主线程做相应的操作。
探索其背后的原理:子线程 handler 主线程 其实构成了线程模型中的经典问题 生产者-消费者模型。 生产者-消费者模型:生产者和消费者在同一时间段内共用同一个存储空间,生产者往存储空间中添加数据,消费者从存储空间中取走数据。
好处: 保证数据生产消费的顺序(通过MessageQueue,先进先出) - 不管是生产者(子线程)还是消费者(主线程)
都只依赖缓冲区(handler),生产者消费者之间不会相互持有,使他们之间没有任何耦合
二、Handler机制的相关类
- Hanlder:发送和接收消息
- Thread(ThreadLocal):存储Looper对象的
- Looper:用于轮询消息队列,一个线程只能有一个Looper
- Message: 消息实体
- MessageQueue: 消息队列用于存储消息和管理消息
1、Thread(ThreadLocal)
Handler机制用到的跟Thread
相关的,而根本原因是Handler
必须和对应的Looper
绑定,而Looper
的创建和保存是跟Thread
一一对应的,也就是说每个线程都可以创建唯一一个且互不相关的Looper
,这是通过ThreadLocal
来实现的,也就是说是用ThreadLocal
对象来存储Looper
对象的,从而达到线程隔离的目的。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
2、Handler
Handler() Handler(Callback callback) Handler(Looper looper) Handler(Looper looper, Callback callback) Handler(boolean async) Handler(Callback callback, boolean async) Handler(Looper looper, Callback callback, boolean async)
2.1 创建Handler大体上有两种方式:
一种是不传Looper
这种就需要在创建Handler
前,预先调用Looper.prepare
来创建当前线程的默认Looper
,否则会报错。
最常见的创建handler
Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } };
在内部调用this(null, false)
;
public Handler(@Nullable Callback callback, boolean async) { ...... mLooper = Looper.myLooper();;//获取Looper,**注意不是创建Looper**! if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue;//创建消息队列MessageQueue mCallback = callback;//初始化了回调接口 mAsynchronous = async; }
Looper.myLooper()
;
//这是Handler中定义的ThreadLocal ThreadLocal主要解多线程并发的问题 // sThreadLocal.get() will return null unless you've called prepare(). static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
sThreadLocal.get() will return null unless you’ve called prepare().
这句话告诉我们get
可能返回null
除非先调用prepare()
方法创建Looper
。下面Looper
里会介绍。
一种是传入指定的Looper
这种就是Handler
和指定的Looper
进行绑定,也就是说Handler
其实是可以跟任意线程进行绑定的,不局限于在创建Handler
所在的线程里。
2.2 async参数
这里Handler
有个async
参数,通过这个参数表明通过这个Handler
发送的消息全都是异步消息,因为在把消息压入队列的时候,会把这个标志设置到message
里.这个标志是全局的,也就是说通过构造Handler
函数传入的async
参数,就确定了通过这个Handler
发送的消息都是异步消息,默认是false,即都是同步消息。至于这个异步消息有什么特殊的用途,我们在后面讲了屏障消息后,再联系起来讲。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
2.3 callback参数
这个回调参数是消息被分发之后的一种回调,最终是在msg
调用Handler
的dispatchMessage
时,根据实际情况进行回调:
// Looper.loop()中会调用 msg.target.dispatchMessage(msg); //Handler.java public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
3、Looper
用于为线程运行消息循环的类。默认线程没有与它们相关联的Looper
;所以要在运行循环的线程中调用prepare()
,然后调用loop()
让它循环处理消息,直到循环停止。
private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } public static void loop() { ... for (;;) { ... } ... } class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { Message msg=Message.obtain(); } }; Looper.loop(); } }
既然在使用Looper
前,必须调用prepare
创建Looper
,为什么我们平常在主线程里没有看到调用prepare
呢?这是因为Android主线程创建的时候,在ActivityThread
的入口main
方法里就已经默认创建了Looper
。
public static void main(String[] args) { ... Looper.prepareMainLooper();//初始化Looper以及MessageQueue ... Looper.loop();// 开始轮询操作 ... } public static void prepareMainLooper() { prepare(false);//消息队列不可以quit synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
prepare
有两个重载的方法,主要看prepare(boolean quitAllowed)
quitAllowed
的作用是在创建MessageQueue
时标识消息队列是否可以销毁, 主线程不可被销毁 下面有介绍
public static void prepare() { prepare(true);//消息队列可以quit } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) {//不为空表示当前线程已经创建了Looper throw new RuntimeException("Only one Looper may be created per thread"); //每个线程只能创建一个Looper } sThreadLocal.set(new Looper(quitAllowed));//创建Looper并设置给sThreadLocal,这样get的 时候就不会为null了 }
4、MessageQueue
MessageQueue
是一个消息队列,Handler
将Message
发送到消息队列中,消息队列会按照一定的规则取出要执行的Message
。Message
并不是直接加到MessageQueue
的,而是通过Handler
对象和Looper
关联到一起。
4.1、创建MessageQueue
创建MessageQueue
以及Looper
与当前线程的绑定
// Looper.java private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed);//创建了MessageQueue mThread = Thread.currentThread();//当前线程的绑定 }
MessageQueue
的构造方法
// MessageQueue.java MessageQueue(boolean quitAllowed) { //mQuitAllowed决定队列是否可以销毁 主线程的队列不可以被销毁需要传入false, 在MessageQueue的quit()方法 就不贴源码了 mQuitAllowed = quitAllowed; mPtr = nativeInit(); }
4.2、Looper.loop()
同时是在main
方法中Looper.prepareMainLooper()
后Looper.loop()
; 开始轮询
// Looper.java public static void loop() { final Looper me = myLooper();//里面调用了sThreadLocal.get()获得刚才创建的Looper对象 if (me == null) {//如果Looper为空则会抛出异常 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; ...... for (;;) {//这是一个死循环,从消息队列不断的取消息 Message msg = queue.next(); // might block if (msg == null) { //由于刚创建MessageQueue就开始轮询,队列里是没有消息的,等到Handler sendMessage enqueueMessage后 //队列里才有消息 // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } ...... try { msg.target.dispatchMessage(msg);//msg.target就是绑定的Handler,详见后面Message的部分,Handler开始 dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } ...... msg.recycleUnchecked(); } }
5、Message
MessageQueue
里的message
是按时间排序的,越早加入队列的消息放在队列头部,优先执行,这个时间就是sendMessage
的时候传过来的,默认是用的当前系统从启动到现在的非休眠的时间SystemClock.uptimeMillis()
。
5.1、创建Message
可以直接new Message
但是有更好的方式Message.obtain
。因为可以检查是否有可以复用的Message
,用过复用避免过多的创建、销毁Message
对象达到优化内存和性能的目地
// Message.java public static Message obtain(Handler h) { Message m = obtain();//调用重载的obtain方法 m.target = h;//并绑定的创建Message对象的handler return m; } public static Message obtain() { synchronized (sPoolSync) {//sPoolSync是一个Object对象,用来同步保证线程安全 if (sPool != null) {//sPool是就是handler dispatchMessage 后 通过recycleUnchecked 回收用以复用的Message Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
5.2、Message和Handler的绑定
创建Message
的时候可以通过Message.obtain(Handler h)
这个构造方法绑定。当然可以在Handler
中的enqueueMessage()
也绑定了,所有发送Message
的方法都会调用此方法入队,所以在创建Message
的时候是可以不绑定的
// Handler.java private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; //绑定 if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
三、Handler发送消息
Handler发送消息的重载方法很多,但是主要只有2种。
sendMessage(Message)
sendMessage
方法通过一系列重载方法的调用,sendMessage
调用sendMessageDelayed
,继续调用sendMessageAtTime
,继续调用enqueueMessage
,继续调用messageQueue
的enqueueMessage
方法,将消息保存在了消息队列中,而最终由Looper
取出,交给Handler
的dispatchMessage
进行处理
// Handler.java public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); } // MessageQueue.java boolean enqueueMessage(Message msg, long when) { ...... synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; } // Looper.java public static void loop() { ...... try { msg.target.dispatchMessage(msg);//msg.target就是绑定的Handler,详见后面Message的部 分,Handler开始 dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } ...... } }
我们可以看到在dispatchMessage
方法中,message
中callback
是一个Runnable
对象,如果callback
不为空,则直接调用callback
的run
方法,否则判断mCallback
是否为空,mCallback
在Handler
构造方法中初始化,在主线程通直接通过无参的构造方法new
出来的为null
,所以会直接执行后面的handleMessage()
方法。
// Handler.java public void dispatchMessage(Message msg) { if (msg.callback != null) {//callback在message的构造方法中初始化或者使用 handler.post(Runnable)时候才不为空 handleCallback(msg); } else { if (mCallback != null) {//mCallback是一个Callback对象,通过无参的构造方法创建出来的handler, 该属性为null,此段不执行 if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); }
四、线程同步问题
Handler
是用于线程间通信的,但是它产生的根本并不只是用于UI处理,而更多的是handler是整个app通信的框架,大家可以在ActivityThread
里面感受到,整个App都是用它来进行线程间的协调。Handler
既然这么重要,那么它的线程安全就至关重要了,那么它是如何保证自己的线程安全呢?
Handler
机制里面最主要的类MessageQueue
,这个类就是所有消息的存储仓库,在这个仓库中,我们如何的管理好消息,这个就是一个关键点了。消息管理就2点:1)消息入库(enqueueMessage
),2)消息出库(next
),所以这两个接口是确保线程安全的主要档口。
MessageQueue.java
源码如下:
boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } // 锁开始的地方 synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } }// 锁结束的地方 return true; }
synchronized
锁是一个内置锁,也就是由系统控制锁的lock unlock
时机的。
synchronized (this)
这个锁,说明的是对所有调用同一个MessageQueue
对象的线程来说,他们都是互斥的,然而,在我们的Handler
里面,一个线程是对应着一个唯一的Looper
对象,而Looper
中又只有一个唯一的MessageQueue
(这个在上文中也有介绍)。所以,我们主线程就只有一个MessageQueue
对象,也就是说,所有的子线程向主线程发送消息的时候,主线程一次都只会处理一个消息,其他的都需要等待,那么这个时候消息队列就不会出现混乱。
另外,在看next函数
Message next() { ...... for (;;) { ...... synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); }}//synchronized 结束之处 // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
next函数
很多同学会有疑问:我从线程里面取消息,而且每次都是队列的头部取,那么它加锁是不是没有意义呢?答案是否定的,我们必须要在next
里面加锁,因为,这样由于synchronized(this)
作用范围是所有this正在访问的代码块都会有保护作用,也就是它可以保证next函数
和enqueueMessage
函数能够实现互斥。这样才能真正的保证多线程访问的时候messagequeue的
有序进行。
小结: 这个地方是面试官经常问的点,而且他们会基于这个点来拓展问你多线程,所以,这个地方请大家重视。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!