【问题标题】:Why main thread's Looper.loop() doesn't block UI thread?为什么主线程的 Looper.loop() 不会阻塞 UI 线程?
【发布时间】:2016-06-26 04:58:13
【问题描述】:

今天我阅读了一些关于 Handler 和 Looper 如何协同工作的博客和源代码。

根据我了解到的情况,我们可以通过使用ThreadLocal 魔法在每个线程上只拥有一个 Looper。通常Handler是在主线程中启动的,否则你必须手动启动或者说,prepareLooper在一个单独的线程上然后循环起来。

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}

真正让我困惑的是主线程中的loop()。正如我在 Looper 的源代码中读到的那样。处理消息队列然后调度消息以供回调处理是一个无限循环。

根据这个https://stackoverflow.com/a/5193981/2290191,Handler和它的Looper在同一个线程中运行。

如果主线程出现死循环,会不会阻塞整个UI系统?

我知道我一定是太傻了才会错过一些东西。但如果有人透露这背后的秘密,那就太好了。

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
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(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();
    }
}

【问题讨论】:

    标签: android multithreading handler looper android-looper


    【解决方案1】:

    实际上主线程中的 Looper 是允许绘图的。当视图无效时,会向主 Looper 传递一条消息,告诉它已请求绘制。当 Looper 处理该消息时,就会发生实际的绘图。阻止 UI 线程的其他活动阻止绘图的原因是它阻止 Looper 处理该绘图消息。

    这或多或少是绘图在任何基于事件的系统中的工作方式,从 Windows 到 Mac 再到 Android。

    为什么不立即绘制而不是发送消息?表现。绘图很慢。如果您为了响应一个事件而进行多项更改,您不想为每一项都重新绘制屏幕。这样做意味着您将所有用于处理单个事件的重绘集中到 1 个重绘中。例如,如果您设置 1 个视图的文本和另一个视图的图像,它们将同时重绘一次。

    【讨论】:

    • 我认为您没有仔细阅读我的问题。我的意思是如果主线程上有for(;;){ }循环,那怎么可能发送消息来绘制UI?
    • 我做到了,我认为您没有理解我的回答。给looper的消息之一导致了平局。 Draw 是发送给该 looper 的特殊消息。
    • 或者换一种说法——你认为的主线程实际上是 Looper 处理消息并调用你的代码来响应它。这是一种称为事件循环或消息循环的技术,在事件驱动编程中很常见。这里详细解释Android的mattias.niklewski.com/2012/09/android_event_loop.html
    • 感谢@Gabe Sechan 该博客真正解释了一切。我曾经用多线程模型来解决所有这些问题。就像事件必须从另一个线程发送并且主线程等待事件处理一样。多么愚蠢!
    • @RyanHoo Android系统使用epoll在线程间发送消息。当消息到来时,epoll 将唤醒线程,处理消息。您可以在源代码ActivityThread 中查看更多详细信息,尤其是mH Handler。
    【解决方案2】:

    这个问题是一个微妙的陷阱。为什么无限循环不会阻塞 UI 线程,因为所有 UI 线程的行为都是从 msg.next 开始的。

    如果没有消息,则表示不需要更新。我们所有的代码都只是一个回调,比如Application onCreate、Activit onCreate、BroadcastReceiver onReceive。

    所有的更新回调都是由消息引起的,而这些消息来自系统服务,比如ActivityManagerService, 输入管理器服务、窗口管理器服务。如果需要更新 UI,android 服务会通过 IPC 向循环发送消息。

    所以无限循环就是无限更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      相关资源
      最近更新 更多