美文网首页
Handler源码分析(笔记)

Handler源码分析(笔记)

作者: 红鲤鱼与绿鲤鱼与驴与鱼 | 来源:发表于2022-03-20 17:05 被阅读0次

    首先Handler大概的工作流程我们要了解一下:


    image.png

    下面这几个类很重要:

    • Handler      发送Message和处理消息(Message)
    • Looper      轮询,不断的从Messagequeue队列中取消息(Message )
    • MessageQueue   存放消息的队列(单链表),要处理的Message就放在这里面
    • ThreadLocal   存放Looper的容器

    从Handler 到 MessageQueue

    handler.sendMessage()开始,点进去看一下,最终会调用到 Handler.enqueueMessage()方法,而且这个方法最后是调用了MessageQueue.enqueueMessage这个方法,并且使用了synchronized来保证多线程同时操作,通过判断延迟时间来确认消息插入到哪,所以这个MessageQueue队列中的Message是有顺序的

        private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
                long uptimeMillis) {
            msg.target = this;
            msg.workSourceUid = ThreadLocalWorkSource.getUid();
    
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    
    //MessageQueue.java
    boolean enqueueMessage(Message msg, long when) {
            if (msg.target == null) {
                throw new IllegalArgumentException("Message must have a target.");
            }
            // 避免多线程同时操作
            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;
        }
    

    上面就是从Handler——>MessageQueue的过程

    接下来Looper

    每个线程只有一个Looper,那么他是怎么做到的呢?

    先从new Handler()开始看起,先不加static关键字

        private /**static*/ final Handler handler = new Handler(Looper.myLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                return false;
            }
        });
    

    先看一下Looper.myLooper()方法,这个方法是从ThreadLocal中获取一个Looper对象,那么这个Looper是什么时候创建的呢,又是如何获取的呢?

    • perpare()方法中保证了每个线程只能有一个Looper,当我们创建多个Looper的时候就会抛出异常Only one Looper may be created per thread”
    • sThreadLocal.set(new Looper(quitAllowed));首先调用ThreadLocal的set方法并且传入一个Looper对象
    • ThreadLocal中set() 方法,获取当前线程,并且拿到当前线程中的ThreadLocalMap,然后map.set(this, value)这句话,是将ThreadLocal作为key ,Looper对象作为value,并存入到ThreadLocalMap

    Looper.java

        static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
           //创建Looper
        private static void prepare(boolean quitAllowed) {
            //保证一个线程中只有一个Looper
            if (sThreadLocal.get() != null) {
                throw new RuntimeException("Only one Looper may be created per thread");
            }
            sThreadLocal.set(new Looper(quitAllowed));
        }
           //获取Looper
        public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
        }
    
    

    ThreadLocal.java

       public void set(T value) {
           Thread t = Thread.currentThread();
           //获取当线程的ThreadLocalMap
           ThreadLocalMap map = getMap(t);
           if (map != null)
               map.set(this, value);
           else
               createMap(t, value);
       }
       //从当前线程的ThreadLocalMap中获取ThreadLocal,这个ThreadLocal中就包含着Looper
       public T get() {
           Thread t = Thread.currentThread();
           ThreadLocalMap map = getMap(t);
           if (map != null) {
               //这个Entry就是相当于ThreadLocal,他其实是一个弱引用WeakReference<ThreadLocal>
               ThreadLocalMap.Entry e = map.getEntry(this);
               if (e != null) {
                   @SuppressWarnings("unchecked")
                   //e.value是获取的 Looper,如果是e.get()返回的是ThreadLocal
                   T result = (T)e.value;
                   return result;
               }
           }
           return setInitialValue();
       }
    

    ThreadLocal.get() 首先获取到当前线程,从当前线程中拿到ThreadLocalMap,这个map是ThreadLocal中的静态内部类,而且这个ThreadLocalMap中保存的就是ThreadLocal和Looper
    注:ThreadLocalMap 的数据结构和HasMap类似

        static class ThreadLocalMap {
            static class Entry extends WeakReference<ThreadLocal<?>> {
                 ...省略内部代码
    
            /**
             * Get the entry associated with key.  This method
             * itself handles only the fast path: a direct hit of existing
             * key. It otherwise relays to getEntryAfterMiss.  This is
             * designed to maximize performance for direct hits, in part
             * by making this method readily inlinable.
             *
             * @param  key the thread local object
             * @return the entry associated with key, or null if no such
             */
            private Entry getEntry(ThreadLocal<?> key) {
                int i = key.threadLocalHashCode & (table.length - 1);
                Entry e = table[i];
                if (e != null && e.get() == key)
                    return e;
                else
                    return getEntryAfterMiss(key, i, e);
            }
            }
        }
    

    Looper中的loop()方法对MessageQueue队列的轮询,可以看到通过MessageQueue.next取出Message,并且调用msg.target.dispatchMessage(msg); 进行消息的分发,那么msg.target是什么呢?
    在Handler 的 enqueueMessage()方法(所有的sendMessage最后都会调用到这个方法)中有这么一句话msg.target = this; ,这里的this就是我们Activity或者子线程中的handler
    我们的handler是Activity中的内部类,因为内部类会持有外部类的引用,所以这里Message中包含着handle自然也会有Activity的引用,这也是为什么当我们的Handler流程没有执行完时Activity关闭了会造成内存泄漏

        /**
         * Run the message queue in this thread. Be sure to call
         * {@link #quit()} to end the loop.
         */
        public static void loop() {
            final Looper me = myLooper();
            if (me == null) {
                throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }
            for (;;) {
                //取出队列中的Message
                Message msg = queue.next(); // might block
             
                ... 省略部分代码
                try {
                   //Message中的target就是handler,所以此处调用的是Handler中的dispatchMessage()方法
                    msg.target.dispatchMessage(msg);
                    if (observer != null) {
                        observer.messageDispatched(token, msg);
                    }
                    dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
                } catch (Exception exception) {
                } finally {
                } 
                msg.recycleUnchecked();
            }
        }
    

    还有一个就是我们的延时消息是如何发送的。这就要看一下我们 MessageQueue中的next()方法了
    next()的部分源码 ,这里也用到了 synchronized 防止多线程同时操作
    延时消息是通过判断这条消息的时间(when)是否比现在时间大,如果大说明还没到该处理的时间,如果小就返回这个Message并返回到Looper的loop()方法中,然后再由handler去分发

    • when 在我们sendMessage时 when = SystemClock.uptimeMillis() + delayMillis() (当前时间+需要延时的时间)
    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) {
                  //判断这条消息的时间是否比现在时间大,如果大说明还没到该处理的时间,
                  // 如果小就返回这个Message并返回到Looper的loop()方法中,然后再由handler去分发
                        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;
                    }
    }
    

    相关文章

      网友评论

          本文标题:Handler源码分析(笔记)

          本文链接:https://www.haomeiwen.com/subject/mwagdrtx.html