Handler原理

2020-06-26  本文已影响0人  还是昵称啊

Handler 原理

一、Handler消息发送机制

1. 发送消息

1.1 添加消息

调用Handler.sendMessageXX方法发送消息,这些方法最终都会调到MessageQueueenqueueMessage方法中,MessageQueue使用一个优先队列来保存添加的Message对象,执行时间越早的Message放的越靠近队头。

//加入新的头结点
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;
    //遍历链表,把最快执行的msg放到表头
    for (;;) {
        prev = p;
        p = p.next;
        if (p == null || when < p.when) {
            break;
        }
        if (needWake && p.isAsynchronous()) {
            needWake = false;
        }
    }
    //插入新的Message节点
    msg.next = p; // invariant: p == prev.next
    prev.next = msg;
}

这样就把一个Message加入到了MessageQueue中。下面要看的就是怎么样取出消息。

1.2 取出消息

Looper.loop()方法中通过一个死循环来不断的从MessageQueue中取出Message

for (;;) {
    Message msg = queue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }
//使本线程休眠
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;
    }

MessageQueue方法中也有一个for循环来从优先队列中找出一个符合条件的Message

[图片上传失败...(image-1acb02-1593160818812)]

二、Looper与线程的数量关系

结论:每条线程只有一个Looper

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中维护了一个ThreadLoacal的静态变量,当调用这个Looperprepare方法时会先判断当前的线程是否有一个Looper的实例,如果没有就创建一个。

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

ThreadLocal维护了一个类似于HashMap的数据结构用线程号作为Key,这样就保证了每条线程只会有一个对应的实例。

所以,Looper是通过ThreadLocal来保证每条线程只有一个Looper实例。如果在同一个线程中多次调用prepare方法就会抛出异常。

三、Handler内存泄露

在实例化Handler时使用匿名内部类来重写handleMessage方法,这个Handler实例就持有了外部类的引用(通常会是一个Activity),在sendMessage时又会使Message引用当前Handler实例,这样Message就会最终引用到Activity实例。由于Handler发送的消息存在延时机制导致线程可能休眠,这样休眠线程中的Message就会一直持有Activity的引用。并且在prepareThreadLocal会持有创建的Looper实例的引用,而静态的ThreadLocal又会被Looper.class持有引用。Looper.class是一个GCRoot所以在可达性分析时就不会释放Activity

[图片上传失败...(image-170ef4-1593160818812)]

四、Handler的使用

1. 主线程上Handler的使用

Looper源码中可以看到需用调用loop方法才能才能从MessageQueue中的取出消息并处理,但是在Activity中使用Handler时,我们并不需要去手动的prepare来调用loop方法。因为在Activity在启动的时候已经由Android自动prepareMainLooper

ActivityThread.main()中已经调用了Looper.prepareMainLooper方法,这个main方法时整个应用启动的入口方法,所以在这个时候就会init主线程中的Looper

2. 在子线程使用Looper

五、多个线程往MessageQueue中发消息如何保证线程安全

使用synchronized关键字对enqueueMessagenext加上当前MessageQueue的锁,这样在多个线程中操作这个MessageQueue时就能保证每次只有一个线程能执行。所以发送Message的delay时间由于等待锁的原因不一定是精确的。

六、如何创建一个Message

通过Message.obtain()方法来获取一个对象。Message中维护了一个Message对象的实例链表,当调用obtain方法时就从链表中取出一个Message实例,并将这个Message的标志位重置。然后返回这个Message实例。当使用完一个Message之后会调用recycleUnCheck()方法来重置这个Message,并将其加入到链表中。这里使用到了享元设计模式。

void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = UID_NONE;
    workSourceUid = UID_NONE;
    when = 0;
    target = null;
    callback = null;
    data = null;

    //最大保存50个
    synchronized (sPoolSync) {
        if (sPoolSize < 50) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

七 、quit和quitSafty的区别

1. quit

这个方法直接移除MessageQueue中所有的Message并将其重置。

private void removeAllMessagesLocked() {
    Message p = mMessages;
    while (p != null) {
        Message n = p.next;
        p.recycleUnchecked();
        p = n;
    }
    mMessages = null;
}

2. quitSafty

这个不会移除当前已经到达执行时间的Message,会让让其正常处理完成,只会移除没有到达处理时间的Message

private void removeAllFutureMessagesLocked() {
    final long now = SystemClock.uptimeMillis();
    Message p = mMessages;
    if (p != null) {
        if (p.when > now) {
            //所有的消息都还不执行,直接将其移除
            removeAllMessagesLocked();
        } else {
            Message n;
            for (;;) {
                n = p.next;
                if (n == null) {
                    return;
                }
                if (n.when > now) {
                    //n节点及之后的节点都还不到执行的时间
                    break;
                }
                p = n;
            }
            p.next = null;
            //将还不到执行时间的message全部移除
            do {
                p = n;
                n = p.next;
                //把target置为null
                p.recycleUnchecked();
            } while (n != null);
        }
    }
}

在执行着两个方法之后会调用nativeWake(mPtr)来唤醒在休眠的next方法,这个方法如果返回一个空的messageLooper就会推出循环。

[图片上传失败...(image-3daee6-1593160818812)]

上一篇 下一篇

猜你喜欢

热点阅读