Handler是怎么实现跨线程通信的

一.主线程里面有几个Handler

在狭义解释里面Handler就是一个类,主线程可以创建无数个。

在广义的解释里面Handler是跨线程通信机制,就只有一套Looper机制,无论创建多少的Handler对象,最后都是基于一个Looper完成通信。

retrofit,eventbus,rxjava与主线程完成跨线程机制都是运用了Looper完成跨线程通信。

android里面与主线程完成跨进程通信都是运用Handler机制。

二.线程间通信的原理是怎么样的?

子线程/主线程    发送消息:handler.sendMessage()     一般在子线程

 子线程/主线程   处理消息:handler.handleMessage()   一般在主线程

子线程发送消息,主线程处理消息这个过程就完成了跨线程通信,背后的原理是啥?如下:

1.往消息队列里面添加消息过程

handler.sendMessage()方法的源码在Handler类里面:

 public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }
  public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
  public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

可以看到整个调用栈是handler.sendMessage()  ---》handler.enqueueMessage() ----》MessageQueue.enqueueMessage。

无论如何都会通过handler.enqueueMessage()方法调用到MessageQueue.enqueueMessage方法里面。

2.从消息队列里面取出消息过程

在MessageQueue的消息如何取出来呢?整体的调用栈ActivityThread.main()---》Looper.looper()--》MessageQueue.next() --》handler.dispatchMessage()---》handler.handleMessage()。

如何判断当前线程是在主线程中取的消息呢?Looper.looper()如果是在主线程被触发,那么后面一系列调用栈也是在主线程中执行。

Looper.looper()是谁调用的?

ActivityThread类的main方法:

 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        ......

        Looper.prepareMainLooper();

        ......
        //一直循环,保障进程一直执行,如果退出,说明程序关闭
        Looper.loop();

        ......
    }

ActivityThread类的main方法先准备好MainLooper然后再执行loop方法一直循环。

Looper.prepareMainLooper方法源码如下:

  public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

prepare方法源码如下:

 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方法里面创建了一个Looper对象,并且把这个对象放在了ThreadLocal里面。

ThreadLocal可参考:一文读懂ThreadLocal的原理及使用场景 - 知乎 (zhihu.com)

Looper对象的创建:

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

可以看到Looper对象创建的时候创建了一个MessageQueue,拿到了当前线程。

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;

        ......
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ......

            try {
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } 
           
            ......
           
        }
    }

可以看到这个方法先获取当前线程对应的Looper,然后开启一个死循环,调用MessageQueue的next方法拿到Message,然后执行msg.target.dispatchMessage(msg),这边的msg.target就是handler,实际上调用了handler的dispatchMessage方法,最后调用handler的handleMessage方法(这个方法通常在上层重写,实现业务逻辑)。

可参考:Handler 源码解析——Handler的创建-CSDN博客

小结:分析到这边我们基本可以明白了,原来在zygoteInit进程的zygoteInit反射创建了ActivityThread进程后,在main方法里面先调用Looper.prepareMainLooper为当前主线程创建了一个Looper,在Looper的构造函数里面创建了MessageQueue。这样一来,主线程有了一个唯一的Looper,而且这个Looper里面有一个唯一的MessageQueue。在ActivtyThread的main方法里面再接着执行Looper的loop方法,在这个loop里面先拿一下我们之前为主线程创建的Looper对象,如果为空则报错,不为空则开启一个死循环一直调用MessageQueue的next方法,直到子线程发送Message过来,才能从MessageQueue里面拿到对应的Message,最后调用Handler的dispatchMessage方法,在dispatchMessage方法里面调用handleMessage处理消息,handleMessage方法通常在业务层被重写,实现收到消息后得业务逻辑。

从我们分析的整体流程可以得到这几个结论:如果要在子线程里面创建Handler,要和在主线程一样:

1.需要再new出Handler前在子线程里面调Looper.prepare(),为子线程创建一个Looper和Message

2.需要调用Looper.loop方法开启死循环接受消息

可参考如何在子线程中创建 Handler?_子线程创建handler-CSDN博客

三.在子线程里面发送消息,在主线程里面接受消息,这个消息跨越两个线程,不会出问题吗?

1.发送消息和取出消息都是一个MessageQueue

我们一般使用Hander是先创建Handler, new Handler(Looper.getMainLooper()),这边sMainLooper就是ActivityThread的main函数执行Looper.prepareMainLooper()创建的。我们new出Handler后在子线程发送消息,MessageQueue.enqueueMessage方法里面的MessageQueue是这边new出来的MessageQueue:

 public Handler(@Nullable Callback callback, boolean async) {
        ......
        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;
    }

主线程里面获取消息也是从这个MessageQueue:

 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;

        ......

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ......

            try {
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } 
            ......
        }
    }

2.发送消息最后执行MessageQueue的enqueueMessage方法和拿出消息的MessageQueue的next方法

MessageQueue的enqueueMessage方法代码如下:

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            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对象加上了同步锁。

Message next() {
        ......
        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方法里面也对当前MessageQueue的类也加上了同步锁。

发送和拿出消息的时候都对同一个MessageQueue对象加上同步锁,确保消息发送和获取没有问题。

3.线程内存共享

线程内存是共享的,比如说在activity里面创建一个list,在主线程和子线程里面都能调用。

MessageQueue就是用于线程共享的,管理meaasge的一个容器,子线程发送消息实际上就是把message添加到MessaageQueue容器里面。

真正实现跨进程通信的原理就是内存共享,message实际上就是一个内存块,跨线程通信实际上就是内存块从子线程带着命令到主线程,然后在主线程中取出这个命令执行的过程。

四.整体流程总结

我们调用handler的sendMessage方法时,就把message放倒了MessageQueue上面。我们的ActivityThread的main方法调用Lopper的loop方法一直循环MessageQueue里面的消息,最后通过handler的dispatchMessage处理掉message。

  • 22
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值