realAndroid开发Android技术知识

Handler原理的整理及相关提问点

2017-12-08  本文已影响52人  蜡笔小州

前言

有关handler的使用网上的教程有很多,并不是很难,在我的前几篇文章中也有简单的介绍过handler使用的整理,但是有关其实现的方式确实面试中非常喜欢问到的。不过以一次我被问到了handler的延迟的实现原理,当时我很郁闷并没有深入的去研究其delay的原理,然而对其handler的流程的学习也是跳过了延迟这部分,说明还是学的不精,后来再我深入学习这部分的时候,发现这里对handler的学习是很有帮助的。

MessageQueue

首先大家都知道,这个是消息队列,是我们管理发布消息的地方,然而我看到网上有人说这个是先进先出的,其实并不是这样,进确实是按照发布的顺序进入的,而出并不是。下面我详细介绍这个类。
Message的功能? MessageQueue主要包含俩个操作,插入、读取,而读取会伴随着删除操作,对应的方法就是enqueueMessage和next。然而尽管我们叫它消息队列,而其内部的实现并不是队列而是单链表的数据结构。下面我们分析一下它的俩个主要方法的源码。

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) {
            //插入消息到链表的头部:MessageQueue实例的头结点Message进行触发时间先后的比较,  
            //如果触发时间比现有的头结点Message短,或者现有的链表头部Message触发时间为0,  
            //亦或是当前MessageQueue中消息链表为空,则这个新的Message作为整个  
            //MessageQueue的头结点,如果阻塞着,则立即唤醒线程处理  
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //插入消息到链表的中间:如果插入消息到链表头部的条件不具备,则依次                  
                //循环消息链表比较触发时间的长短,然后将消息插入到消息链表的合适位置。接着  
                //如果需要唤醒线程处理则调用C++中的nativeWake()函数.  
                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;
    }
emmmmmm.jpg

延迟进入队列?这里为了方便理解,我将官方的注释改为中文理解的注释。我们知道,我们所有的post,postDelay,sendMessage,sendMessageDelay都会最终调用MessageQueue的enqueueMessage方法,也就是插入队列,可以看到我们在插入队列时候并没有任何的阻塞操作和延迟操作,其中主要的内容只有一个if else和一个循环,和一个唤醒操作,也就是说网上说的延迟进入消息队列的说法是错误的。而这个方法的返回值是其进入到了队列中就会返回true。

先进先出?其message在发布后,会马上进入到消息队列中,并不会延迟进入。其中if和else可以参照注释,if中是有消息进入并不伴随着延迟,就是要立即looper的消息,我们的enqueueMessage会使用if将它插入到链表的头部,而else呢,根据代码和注释它是根据其delay的时间,在使用遍历将其插入到链表的合适的位置,所以说消息队列是不存在先进先出的。

唤醒什么?而needWake是什么呢,顾名思义,他是需要唤醒,也就是这个标识量为true的时候,队列处于阻塞状态,需要唤醒,在if的neekWake=mBlocked中就是将阻塞的标识给了需要唤醒这个标识。

所以,既然我们不是先进先出了,那么我先postDelay(,3000),然后马上post的话,那么后面的消息会阻塞3000ms吗?当然不会,有些人会误认为它是队列,先进先出,然而在后面的消息到达后,我们的队列根据他的唤醒标识,去唤醒队列的阻塞,将这个消息插入到消息队列的头部,如果没有延迟则立刻调用looper()。


让我好好爆爆你.jpg

下面我们看下next方法的实现。

Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            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);
            }

            // 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的代码主要功能是从队列中取出消息,然后再删除对应的消息,我们可以看到这里面有个循环,就是其实现取消息,整个循环是实现了取,而looper中的循环是让MessageQueue不停地取,也就是说这个next中如果取到了消息,并删除,然后返回message,这个循环就停止,也就是取消息成功!而我们知道looper中还有一个循环,便实现了不停的取,这个取成功了继续去取,一个轮询,俩个循环不能混淆。

这里有阻塞?next的调用就是在looper中。我们可以很亲切的官方注释说这个方法会阻塞,我们在next中看到了这样一个方法,nativePollOnce(ptr, nextPollTimeoutMillis);,这个方法就是实现了阻塞,具体的实现是在C层,介绍一下这个方法。
1.如果nextPollTimeoutMillis=-1,一直阻塞不会超时。
2.如果nextPollTimeoutMillis=0,不会阻塞,立即返回。
3.如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。


666666.jpg

这个真的是厉害,本身像wait一样但是还是sleep的功能,而且如果有新消息到来时,还可以在enqueueMessage中通过nativePollOnce进行唤醒,那么看到这里,我们应该知道了这个postDelay如何实现的延迟了吧。

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);
}

阻塞逻辑在nativePollOnce里面?是的,时间未到,next中则去改变这个nextPollTimeoutMillis,然后根据这个标识,在nativePollOnce方法内部去通过逻辑实现是否要去阻塞,阻塞多久。

sleep和postdelay的区别?那么网上有一种区分sleep和postDelay的说法看来是错误的,他们说sleep实现了阻塞而delay没有,实际上并不是,sleep是线程睡眠,而delay也是实现了阻塞,只不过为什么delay后面的代码还是立即执行,原因就是之前提到的enqueueMessage中,我们新的消息插入到了队列头,我们知道整个android的ui线程也是一个消息,我们在postdelay后立刻setText,而setText的这个消息边会唤醒这个队列,从而我们以为它只是延迟而没有阻塞。

主线程不是卡主了?那么这里有人提问了,比如我在一个线程中去阻塞,比如主线程,他不就卡主了嘛?当然不会,我们在主线程new Handler.postDelay(new MyRunable,3000);后会有大量的操作进入我们主线程的这个looper当中,当然我们的主线程有且只有这一个loop(可以不在子线程创建looper就不会有了...),我们的手的各种操作都会触发这个looper,我们的屏幕的16ms的刷新也会触发,所以我们的这个looper这个循环不会停止,主线程停止了不就结束了嘛,在我们的ActivityThread中这个循环会不停的下去,去发消息,去触发生命周期,当然除非我们在生命周期去进行大量的耗时操作,这个ui线程才会真正意义上的阻塞,而5秒没有唤醒就是触发了ANR。然而我们的主线程的很多时候都阻塞的,不然它的开销是太大的,需要的时候唤醒就好了。

子线程呢?这里有人会问如果我在一个子线程,让它的looper也在这个子线程,它的enqueueMessage也在这个子线程,它阻塞了怎么办?我们可以试一下。
当然我们直接在子线程中去new Handler().postDelay是无法实现的,因为子线程的looper还来不及去创建便去通过looper去操作消息会抛出异常。
这里我们可以使用handlerThread,重写里面的run方法。

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
            Log.i("zhou","!!!"+getThreadId());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.i("zhou","3000");
                    Log.i("zhou","~~~"+getThreadId());
                }
            },3000);
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
有病.gif

作者是不是有病?好嘛,真的是有病,不过我们试一下。他是可以打印出来内容的,但是不是阻塞了嘛?enqueue不像是主线程不停有新消息进入去唤醒,我们别忘了之前说的。如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。也就是说唤醒的方式有俩种,一种是在插入链表的时候,一种是延迟时间到达的时候。所以理解handler的阻塞对理解handler是很有帮助的。

Looper

looper是什么?网上说looper是一个泵,这么说挺有意思的,Looper在消息机制中扮演着消息循环的角色,具体说它就是不停地从MessageQueue中查看是否有新消息,通过轮询next方法去实现不停地查看,如果有就通过next返回,没有就通过标志量-1而阻塞。这里我们知道了,looper在哪个线程,里面的dispatchMessage就是哪个线程,其回调就是哪个线程,也是通过这种方式实现的线程通讯。
looper怎么退出?MessageQueue唯一跳出循环的方式是MessageQueue的next方法返回null,这样looper会通过quit或者quitSafely方法来退出。

public final class Looper {
    /*
     * API Implementation Note:
     *
     * This class contains the code required to set up and manage an event loop
     * based on MessageQueue.  APIs that affect the state of the queue should be
     * defined on MessageQueue or Handler rather than on Looper itself.  For example,
     * idle handlers and sync barriers are defined on the queue whereas preparing the
     * thread, looping, and quitting are defined on the looper.
     */

    private static final String TAG = "Looper";

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;
    private long mTraceTag;

    /* If set, the looper will show a warning log if a message dispatch takes longer than time. */
    private long mSlowDispatchThresholdMs;

     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

    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));
    }

    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    /**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

    /**
     * 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.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // 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);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

    /**
     * Return the {@link MessageQueue} object associated with the current
     * thread.  This must be called from a thread running a Looper, or a
     * NullPointerException will be thrown.
     */
    public static @NonNull MessageQueue myQueue() {
        return myLooper().mQueue;
    }

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

    /**
     * Returns true if the current thread is this looper's thread.
     */
    public boolean isCurrentThread() {
        return Thread.currentThread() == mThread;
    }

    /**
     * Control logging of messages as they are processed by this Looper.  If
     * enabled, a log message will be written to <var>printer</var>
     * at the beginning and ending of each message dispatch, identifying the
     * target Handler and message contents.
     *
     * @param printer A Printer object that will receive log messages, or
     * null to disable message logging.
     */
    public void setMessageLogging(@Nullable Printer printer) {
        mLogging = printer;
    }

    /** {@hide} */
    public void setTraceTag(long traceTag) {
        mTraceTag = traceTag;
    }

    /** {@hide} */
    public void setSlowDispatchThresholdMs(long slowDispatchThresholdMs) {
        mSlowDispatchThresholdMs = slowDispatchThresholdMs;
    }

    /**
     * Quits the looper.
     * <p>
     * Causes the {@link #loop} method to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @see #quitSafely
     */
    public void quit() {
        mQueue.quit(false);
    }

    /**
     * Quits the looper safely.
     * <p>
     * Causes the {@link #loop} method to terminate as soon as all remaining messages
     * in the message queue that are already due to be delivered have been handled.
     * However pending delayed messages with due times in the future will not be
     * delivered before the loop terminates.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p>
     */
    public void quitSafely() {
        mQueue.quit(true);
    }

    /**
     * Gets the Thread associated with this Looper.
     *
     * @return The looper's thread.
     */
    public @NonNull Thread getThread() {
        return mThread;
    }

    /**
     * Gets this looper's message queue.
     *
     * @return The looper's message queue.
     */
    public @NonNull MessageQueue getQueue() {
        return mQueue;
    }

    /**
     * Dumps the state of the looper for debugging purposes.
     *
     * @param pw A printer to receive the contents of the dump.
     * @param prefix A prefix to prepend to each line which is printed.
     */
    public void dump(@NonNull Printer pw, @NonNull String prefix) {
        pw.println(prefix + toString());
        mQueue.dump(pw, prefix + "  ", null);
    }

    /**
     * Dumps the state of the looper for debugging purposes.
     *
     * @param pw A printer to receive the contents of the dump.
     * @param prefix A prefix to prepend to each line which is printed.
     * @param handler Only dump messages for this Handler.
     * @hide
     */
    public void dump(@NonNull Printer pw, @NonNull String prefix, Handler handler) {
        pw.println(prefix + toString());
        mQueue.dump(pw, prefix + "  ", handler);
    }

    /** @hide */
    public void writeToProto(ProtoOutputStream proto, long fieldId) {
        final long looperToken = proto.start(fieldId);
        proto.write(LooperProto.THREAD_NAME, mThread.getName());
        proto.write(LooperProto.THREAD_ID, mThread.getId());
        proto.write(LooperProto.IDENTITY_HASH_CODE, System.identityHashCode(this));
        mQueue.writeToProto(proto, LooperProto.QUEUE);
        proto.end(looperToken);
    }

    @Override
    public String toString() {
        return "Looper (" + mThread.getName() + ", tid " + mThread.getId()
                + ") {" + Integer.toHexString(System.identityHashCode(this)) + "}";
    }
}

它的构造方法中会创建一个MessageQueue,然后保存线程的对象。
子线程记得要创建looper looper.prepare就可以创建 looper可以开启循环,也可以通过HandlerThread它在run里面已经给我们创建了,并且还伴有wait方法在控制异常。
我们可以看到looper里面就是一个循环,去next(),然后去msg.target.dispatchMessage,在去回调handleMessage()。

转载请注明出处:http://www.jianshu.com/p/bed3c5192a55

上一篇下一篇

猜你喜欢

热点阅读