我终于读懂了Handler(一)

在Android中提到线程间通信那么一定离不开Handler。那么Android中是如何利用Handler进行线程间通信的?
假如A线程要给B线程发送100条消息。
我们可以这样理解:

  1. A线程要做的事情(子线程,通常会伴有耗时操作)
    • 构造消息
    • 发送消息
  2. B线程要做的事情 (主线程, 回调handleMessage(Message msg)方法,在此方法中接收到子线程发送的消息)
    • 创建消息队列MessageQueue(这100条消息不可能一下子处理完,要一个一个处理)
    • 用一个Looper从消息队列中取出消息,处理消息。


handler原理图

当然现在看这个图可能会:哦,原来是这样。读完整篇文章可能会:哦,原来是这样!

1.Handler线程间通信例子


    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){

            }
        }
    };

    void sendMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message=handler.obtainMessage();//构造消息
                message.what=1;//为消息设置标志
                handler.sendMessage(message);
            }
        }).start();
    }

在主线程中会默认调用Looper.prepare()和Looper.loop()两个方法。

2.Looper.prepare()很重要


以一个简单的线程间通信为例,首先看默认调用的Looper.prepare()方法
查看Looper.prepare()会跳转到

    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));
    }
    //查看Looper的构造
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

这些都是Looper类中的内容,我们可以看到第7行创建了一个Looper对象,Looper的构造方法里面创建了MessageQueue对象(消息队列),handler发送的消息都会放入消息队列中来一一处理。

  利用ThreadLocal保证了Looper对象只对当前线程可见,ThreadLocal实现原理即类似一个散列表的结构,本例中是以当前线程mThread和一个Looper对象为键值对确保我们每次使用ThreadLocal的get方法得到的Looper对象始终是同一个。
  第一行的对象sThreadLocal以static final修饰又保证了这个sThreadLocal在整个应用程序中唯一的一份内存地址,不会有新的sThreadLocal对象创建。这样确保了多线程handler使用过程中每个线程的Looper是独一份的,而sThreadLocal又可以存储多个(key->当前线程,value->Looper对象)的键值对,从而保证了线程安全。

难理解点儿:保证当前线程只有一个Looper实例和消息队列的实现和散列表的封装

3.发送消息

3.1 handler.sendMessage


接下来看handler.sendMessage(message):

    它会跳转到这里
    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);
    }

   sendMessage时调用handler中的sendMessageAtTime(Message msg, long uptimeMillis)方法把一个个消息填到消息队列中,最终会通过enqueueMessage(queue, msg, uptimeMillis)调用到MessageQueue中的enqueueMessage()方法,这样消息就存放进入消息队列中了。 把消息存放到消息队列里面后,接下来就开始对消息一个一个进行处理。

我们可以看到第3行 MessageQueue queue = mQueue,这里有直接就赋值了消息队列的对象,这个消息队列是怎么来的?

3.2 消息队列和Looper的获取

//我们看一下队列是如何获取到的
    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    //Looper中的静态方法
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

   我们可以看到第12行通过调用Looper的静态方法获取到了Looper的实例对象,第18行Looper通过mLooper.mQueue把子线程中的Looper实例赋值。    所以我们现在应该明白为什么Looper.prepare()要先执行了,正是因为prepare()中创建了子线程中的唯一一个Looper对象和消息对象,所以在sendMessage时才会有已经创建好的消息队列来存放。/>

4.处理消息

4.1 loop()方法


调用方法Looper.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 lotng ident = Binder.clearCallingIdentity();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        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 traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

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

  里面值得我们关注的就是一个for形式的死循环(23行),接下来Message msg = queue.next()从消息队列中取消息,为空的话这个线程就生命周期就结束了,代码跑完了嘛。不为空时msg.target.dispatchMessage(msg)处理消息,这个target是一个handler,它调用dispatchMessage方法最后回调到主线程中Handler重写的handleMessage()方法,执行完毕就再跑for循环的内容,直至从消息队列取到消息为空,线程生命结束。

for循环里面还有一个点比较值得探究,24行队列调用了next()方法

4.2 queue.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;
        }
    }

   nativePollOnce(ptr, nextPollTimeoutMillis)这很明显是一个native方法,它的作用就是阻塞当前线程,nextPollTimeoutMillis小于0的时候就会一直被阻塞直至被唤醒,等于0就不会阻塞,大于0就是阻塞的时间毫秒数。

我们都知道一个线程处于休眠状态,如果要将它唤醒,一般有两种方式。一种是其他线程来唤醒,另一种就是内核来唤醒它。这里就是利用的内核唤醒的方式,利用linux的epoll机制唤醒该线程。

4.3 enqueueMessage()消息入队

MessageQueue中的enqueueMessage()

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

49行的nativeWake(mPtr),可以唤醒nativePollOnce()的阻塞。
易混点:线程阻塞的情况,msg.target.dispatchMessage(msg)方法回调时真正要看的是在主线程实例化Handler是是否指定了Looper实例和Callback。

5. 子线程中创建Handler对象

刚刚我们将的那么多都是探究的主线程中创建的Handler对象,它会默认执行Looper.prepare()和Looper.loop()方法。可是子线程中就需要我们自己手动执行了。通常我们子线程创建Handler对象都会这样做:

    class LooperThread extends Thread {

        public Handler handler;

        @Override
        public void run() {
            super.run();
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);

              
                    }
                }
            };
            Looper.loop();
        }
    }

如果你没有先执行Looper.prepare()方法,肯定会抛出异常,因为Looper对象还没有创建。3.2中做出了判断

if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }

6.Handler切换线程小结

总结一下Handler切换线程的流程:

  其实我感觉好多博客对handler发消息的理解有些谬误,不乏一些大牛的博客(当然也可能是我理解错了)。
  在主线程中实例化handler用的是默认的new Handler()方法,它的Looper对象用的就是主线程的Looper。因为一般情况下Handler实例化是先执行的,而它实例化过程中会获取Looper对象,这个时候子线程还没创建它哪来的子线程对应的Looper对象。
  而在子线程实例化handler的时候,大多数博客分析的就符合情况了。不过发送消息的流程还是通用的。

  当某个线程使用hanlder机制时,首先会调用Looper.prepare()方法创建当前线程的Looper对象和MessageQueue对象,构造消息,然后sendMessage(),把消息存放到消息队列中,再调用Looper中的loop()方法循环处理消息,如果消息队列为空就会阻塞当前线程,当消息队列中进入消息线程会被唤醒。Looper.loop()方法就会循环处理消息,并调用msg.target.dispatchMessage(msg)方法触发主线程handleMessage()的回调。

这里分析了简单的Handler发送消息的机制,多个handler在多线程中的应用接下篇———我终于读懂了Handler(二)

原文地址:https://www.cnblogs.com/dearnotes/p/15734759.html