Android消息机制原理分析

Android的消息机制分析

上次,我分析了Handler,MessageQueue和Looper是如何协同工作的,这次做这个深入的理解:
上次连接: https://blog.csdn.net/qq_36391075/article/details/80637473

ThreadLocal的工作原理

ThreaddLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储之后,只有在指定线程中可以获取到存储的数据,对于其他线程来说无法获取到数据。

一般来说,如果某些数据是以线程为作用域的并且不同的线程具有不同的数据副本的时候,就可以考虑使用ThreadLocal。

对于Handler来说,它需要获取当前线程的Looper,我们知道,Looper的作用域就是线程,并且不同的线程有不同的Looper,而Handler就是通过ThreadLocal获取到该线程的Looper。

首先我们看一下TreadLocal的使用:

  private ThreadLocal<Boolean> mBooleanThreadaLocal  = new ThreadLocal<>();
  mBooleanThreadaLocal.set(true);
    Log.d(TAG,"[Thread#main]mBooleanThreadLocal = " +mBooleanThreadaLocal.get());

    new Thread("Thread#1"){
        @Override
        public void run() {
            mBooleanThreadaLocal.set(false);
            Log.d(TAG,"[Thread#1]mBooleanThreadLocal = " +mBooleanThreadaLocal.get());
        }
    }.start();

    new  Thread("Thread#2"){
        @Override
        public void run() {
            Log.d(TAG,"[Thread#1]mBooleanThreadLocal = " +mBooleanThreadaLocal.get());
        }
    }.start();

我们看一下打印的log:

从上面的日志中可以看出,虽然在不同线程中访问的是同一个ThreaddLocal对象,但是它们通过ThreadLocal获取到的值是不一样的。ThreadLocal为什么那么神奇呢?我们一步一步的分析。

ThreadLocal是一个泛型类:

public class ThreadLocal<T>

首先我们看看它的set方法:

 /**
 * Sets the current thread's copy of this thread-local variable
 * to the specified value.  Most subclasses will have no need to
 * override this method, relying solely on the {@link #initialValue}
 * method to set the values of thread-locals.
 *
 * @param value the value to be stored in the current thread's copy of
 *        this thread-local.
 */
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

首先会得到当前的线程,然后通过getMap方法得到当前线程中的ThreadLocal数据:

 /**
 * ThreadLocalMap is a customized hash map suitable only for
 * maintaining thread local values. No operations are exported
 * outside of the ThreadLocal class. The class is package private to
 * allow declaration of fields in class Thread.  To help deal with
 * very large and long-lived usages, the hash table entries use
 * WeakReferences for keys. However, since reference queues are not
 * used, stale entries are guaranteed to be removed only when
 * the table starts running out of space.
 */
static class ThreadLocalMap 

ThreadMap是ThreadLocal中的静态内部类,通过它的英文解释,我们可以知道ThreadLocalMap是一个专门为保存当前线程值的hashMap。

如果map的值为null,那么就需要进行初始化的操作,并将值存进去。

在ThreadLocalMap中有一个数组:

 static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;

        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
    }

    /**
     * The initial capacity -- MUST be a power of two.
     */
    private static final int INITIAL_CAPACITY = 16;

    /**
     * The table, resized as necessary.
     * table.length MUST always be a power of two.
     */
    private Entry[] table;

ThreadLocal的值就存在这个table当中。然后我们看看他的set方法:

private void set(ThreadLocal<?> key, Object value) {

        // We don't use a fast path as with get() because it is at
        // least as common to use set() to create new entries as
        // it is to replace existing ones, in which case, a fast
        // path would fail more often than not.

        Entry[] tab = table;
        int len = tab.length;
        int i = key.threadLocalHashCode & (len-1);

        for (Entry e = tab[i];
             e != null;
             e = tab[i = nextIndex(i, len)]) {
            ThreadLocal<?> k = e.get();

            if (k == key) {
                e.value = value;
                return;
            }

            if (k == null) {
                replaceStaleEntry(key, value, i);
                return;
            }
        }

        tab[i] = new Entry(key, value);
        int sz = ++size;
        if (!cleanSomeSlots(i, sz) && sz >= threshold)
            rehash();
    }

我们可以看到,它使用ThreadLocal的hashcode和table的length-1得到数组的首,然后遍历得到最后一个,然后将最后一个加在tab的后面,然后将新的tab赋值给table。

然后我们看看ThreadLocal的get方法:

 /**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 */
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();
}

我们可以看到,也是先获取到当前的线程,然后根据当前线程得到ThreadLocalMap,如果map不为null,就从map中获取Entry,然后返回值。
如果map为null,那么就返回初始值,默认情况下为null: 这个方法可以重写

private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

 protected T initialValue() {
    return null;
}

从ThraedLocal的set方法和get方法可以看出,它们所操作的的对象都是当前线程的ThreadLocalMap的table数组,因此在不同线程中访问同一个ThreaddLocal的set方法和get方法,它们对ThreadLocal所做的读/写操作仅限于各自线程的内部。

给我的感觉,ThreadLocal只是一个中间媒介,其他实际上操作的是当前线程。

消息队列的工作原理

消息队列在Android中指的是MessageQueue,MessageQueue主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作。插入和读取分别对应的方法为enqueueMessage和next。尽管MessageQueue叫做消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来进行维护的。

首先,我们先看看MessageQueue的插入:

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

通过上面的代码分析,我们可以看到,其实MessageQueue消息的插入其实就是单链表的插入。

然后我们再看看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 
    int nextPollTimeoutMillis = 0;
    //用来描述当消息队列中没有新的消息需要处理时,当前线程需要进入睡眠等待的时间。
    //值等于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;
            //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方法是一个无线循环的方法,如果消息队列中没有消息,那么next方法就会一直阻塞在这里。当有新消息来到的时候,next方法会返回这条消息并将其从单链表中移除。
在获取消息的时候,会检查该消息是否准备好了,也就是检查它的处理时间,如果没有准备好,就会计算当前线程下一次调用成员变量函数nativePollOnce()时,如果没有新的消息需要处理那么当前线程需要进入睡眠等待状态的时间,以便可以在指定的时间点对接下来的消息进行处理。
如果消息准备好了,就会对消息进行处理,并且会将mMessage指向下一个需要处理的消息。

Looper的工作原理

Looper在Android的消息机制中扮演者消息循环的角色,具体来说就是它会不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。
首先看它的构造方法:

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

可以看到,在Looper初始化的时候,会创建一个MessageQueue消息队列,和保存当前的线程对象。

我们知道,Handler的工作需要Looper,没有Looper的线程就会报错,那么怎么为一个线程去创建一个Looper呢,通过Looper.prepare()就可以为当前线程创建一个Looper:

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

在prepare的时候,我们可以看到,会调用ThreadLocal的get方法检查当前在线程的Looper是否存在。
然后调用Looper.loop()来开启消息循环

 new Thread(){
        @Override
        public void run() {
            Looper.prepare();
            Handler handler = new Handler();
            Looper.loop();
        }
    };

Looper是可以退出的。Looper提供了quit和quitSafely来退出一个Looper,二者的区别是:quit是直接退出Looper,quitSafely只是设定一个退出标记,然后把消息队列中的已有的消息处理完毕后才安全的退出。
Looper退出后,handler再发动消息就会失败,Handler的send方法会返回false。

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

loop方法中是一个死循环,唯一跳出该循环的方法就是MessageQueue的next返回的Message为null,也就是Looper的quit方法被调用的时候,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列的退出,当消息队列被标记为退出状态的时候,它的next方法就会返回null。
loop方法会调用MessageQueued额next方法来获取消息,而我们知道,MessageQueue的next方法是一个阻塞操作,当没有消息的时候,next方法会一直阻塞在那里,也导致loop方法一直阻塞。如果MessageQueue的next方法返回了消息,Looper就会处理这条消息,也就是msg.target.dispatchMessage(msg);,这里的target我们知道是handler,所以最终交给了Handler的dispatchMessage(msg)来处理方法,这样就带代码逻辑成功的切换到了声明Handler的线程中去了。

handler的工作原理

Handler的工作主要包含消息的发送和消息的接收。消息的发送可以通过post的一系列方法以及send的一系列方法来实现,post的一系列方法最终会调用send的一系列方法。

发送一条消息的典型过程如下:

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

我们可以看到,Handler发送消息的过程仅仅是将该Handler保存在Message中,并且向消息队列中插入了一条消息。这样,MessageQueue的next就会返回这条消息给Looper,Looper接收到这条消息后就开始处理,即Handler的dispatchMessage方法会被调用,这样Handler就进入了消息处理阶段:

` public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}`

根据上次的分析,我们知道在这个方法中,会先检查Message的callback,这个callback就是一个Runnable对象,实际上就是我们调用Hanlder的post方法发送消息的时候传入的Runnable:

 private static void handleCallback(Message message) {
    message.callback.run();
}

所以最终会调用run方法。

齐次会检查mCallback是否会null,不为null就调用mCallback的handleMessage方法来处理,mCallback是一个接口:

 public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public boolean handleMessage(Message msg);
}

最终会调用handleMessage方法。

最后我们看看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();
    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;
}

猜你喜欢

转载自blog.csdn.net/qq_36391075/article/details/80720519