Android中的消息机制一(Handler、Looper、ThreadLocal、MessageQueue)

Android消息机制

Android中的消息机制主要是指Handler机制、消息队列、消息循环处理的一种工作方式,通过该消息机制可以实现进程间通信、任务在线程间的切换。涉及到的类主要有Handler、Looper、ThreadLocal(线程相关)、MessageQueue,这四个类进行协同工作,来处理消息。

Handler

Handler的作用是将一个任务切换到指定的某个线程中去执行,通过它的一系列send方法和post方法将消息发送到消息队列中,然后通过Looper循环去取出这些消息并处理,这一系列发送消息的方法最终会调用到sendMessageAtTime方法,sendMessageAtTime的源码:

 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);
        }
        //往消息队列(MessageQueue )中插入消息
        return queue.enqueueMessage(msg, uptimeMillis);
    }

Handler的创建会依赖于当前线程的Looper,如果当前线程没有Looper那么就会抛出异常。Handler的构造方法:

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

        //mLooper为null就会抛出异常
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
           }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Looper

Looper是一个无限循环,循环取消息队列中的消息进行处理,如果消息队列中没有消息,那么Looper就会阻塞,直到有新消息的到来才会被唤醒。每一个线程都对应一个自己的Looper,线程默认是没有Looper的,但是在应用启动的时候ActivityThread会初始化主线程的Looper,所以主线程可以认为默认是有Looper的,这也就是为什么主线程中可以直接使用Handler的原因。子线程是没有Looper的,如果要在子线程中使用Looper就需要手动创建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");
        }
        //创建Looper对象
        sThreadLocal.set(new Looper(quitAllowed));
    }


 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指代的是发送消息的Handler
                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();
        }
    }

通过分析上面的源码可知,在prepare方法中会创建Looper的对象,在loop方法中通过一个无条件的for循环来实现无限循环,通过MessageQueue的next方法获取消息,如果没有消息就通过MessageQueue的next方法实现阻塞等待新消息到来。
msg.target.dispatchMessage(msg):这行代码是消息的分发处理,msg.target指代的是发送该消息的Handler,这个时候该消息就切换到发送消息的Handler中去处理了,也就意味着该任务切换到该Handler所在的线程中处理了。比如,在线程1中的run方法里创建一个Handler,然后在线程2中调用该Handler发送消息到Handler对应的消息队列中,然后在由Handler对应的Looper取出该消息交给该Handler的dispatchMessage(在Handler对应的线程里面执行的,也就是线程1)方法分发处理该消息,这样任务就从线程2切换到线程1中处理了。
Looper可以调用quit(立刻退出)和quitSafely(消息执行完才退出)来退出,如果是自己在子线程中手动开启的looper,消息执行完的时候一定要退出Looper(当前线程才能终止),否则这个线程就一直不会结束(Looper一直在循环)。

ThreadLocal

上面介绍Looper的时候我们知道,Looper是跟线程相绑定的,也就是一个线程对应一个自己私有的独立的Looper。那么如何实现这个功能呢,ThreadLocal可以解决这个问题。
ThreadLocal意思是线程本地存储,ThreadLocal里面存储的数据是仅当前线程自己所私有的,其他线程无权访问,多个线程访问同一个ThreadLoacl对象,通过ThreadLoacl的set和get方法的操作,每个线程是相互不影响的。那么就看下ThreadLoacl的set和get方法的源码是如何实现的:

ThreadLocal的set方法:

 public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

由上面的set方法可知,调用ThreadLocal的set方法的时候,会先获取到当前调用的线程,然后会获取线程自己的ThreadLocalMap (t.threadLocals,线程内部的一个变量,每个线程都有一份自己的),然后将值存储到ThreadLocalMap 里面,所以可以知道,每个线程的ThreadLocalMap是完全独立的、相互没有影响的,只有当前线程所拥有,也只能当前线程能操作。

ThreadLocal的get方法:

 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

上面的get方法同样是,先根据当前线程获取自己的ThreadLocalMap ,然后在从ThreadLocalMap 里面获取之前set的值,因为ThreadLocalMap 每个线程都有自己的单独的一份,所以获取的值,也是当前线程独有的,不受其他线程的影响。
通过上面的分析可以知道,ThreadLocal确实能实现跟线程绑定的功能,我们在分析Looper的时候发现,Looper的存储和获取是通过ThreadLocal的set、get方法实现的,所以Looper是跟线程进行绑定的,一个线程对应一个自己的单独的Looper。

MessageQueue

消息队列MessageQueue是单链表结构,MessageQueue通过里面的enqueueMessage和next两个方法实现消息的插入和读取,enqueueMessage方法是往消息队列中插入消息,next方法是从消息队列中取出消息返回并从消息队列中删除该消息。next方法里面有个for(;;)死循环,如果没有消息,next方法会阻塞一直等待新消息的到来。MessageQueue的创建是在Looper的构造方法中创建的。下面是相关源码:

扫描二维码关注公众号,回复: 1762357 查看本文章

Looper构造方法:

 private Looper(boolean quitAllowed) {
        //创建一个MessageQueue对象
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

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.

            //如果之前next方法是阻塞状态,那么有新消息到来时会进行唤醒
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

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 {
                     //msg为null(没有消息)
                    // 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方法中调用了nativePollOnce(ptr, nextPollTimeoutMillis)方法,这个方法是一个Native方法,这个方法会出现阻塞,nextPollTimeoutMillis这个参数有三种值:

  • 如果nextPollTimeoutMillis=-1,一直阻塞不会超时。
  • 如果nextPollTimeoutMillis=0,不会阻塞,立即返回。
  • 如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。

上面的代码中显示,如果 msg==null,也就是没有消息的时候,nextPollTimeoutMillis = -1,这个时候next会阻塞

在enqueueMessage方法中调用了nativeWake(mPtr)方法,如果之前消息循环在阻塞状态下,有新消息到来时,会调用该方法进行唤醒。

上面介绍了消息机制相关的一些类,至于Handler机制中消息传递的整体流程,放到下篇文章中进行总结,文章链接: https://blog.csdn.net/huideveloper/article/details/80655357

猜你喜欢

转载自blog.csdn.net/huideveloper/article/details/80646267