关于Looper.loop()死循环???

一直以为自己把Android消息机制弄明白了,直到前段时间面试,发现还有细节方面没搞清楚,查找相关资料,此篇文章是对Looper对象是怎么获取的,线程里的ThreadLocal,Looper.loop()死循环问题等的理解和总结。
关于消息机制中Handler,Looper,MessageQueue关系请查看以前的文章https://blog.csdn.net/liuwei187/article/details/76070350

Looper对象是怎么获取到的

大家都知道在子线程中使用hander需要先调用Looper.prepare()创建一个Looper对象。
源码如下:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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));
    }
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

在prepare()方法中先通过sThreadLocal.get()方法获取Looper,如果不是null抛出异常,从而也就证明了一个Thread对应一个Looper;如果是null的话则创建一个Looper对象,并将Looper对象放在了ThreadLocal中,在创建Looper的构造方法中会创建MessageQueue消息队列。
所以Looper对象存储在了ThreadLocal中,那么ThreadLocal是什么呢?

ThreadLocal

提到ThreadLocal,大家都知道ThreadLocal是线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。
那ThreadLocal是怎么实现的呢?
ThreadLocal的部分源码如下:

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

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

        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
}
...
}

ThreadLocal中,有一个静态内部类ThreadLocalMap,Entry类是ThreadLocalMap的静态内部类,用于存储数据,而且Entry继承了WeakReference,也就是说每个Entry对象都有一个ThreadLocal的弱引用(作为key),这是为了防止内存泄露。一旦线程结束,key变为一个不可达的对象,这个Entry就可以被GC了。
而在Thread中,每个Thread里面都有一个ThreadLocal.ThreadLocalMap成员变量,所以每个线程通过ThreadLocal.ThreadLocalMap与ThreadLocal绑定,确保每个线程访问到的thread-local variable都是本线程的。

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

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

大家都知道调用Looper.loop()方法会使Looper一直在不断的从消息队列中通过MessageQueue的next方法获取Message,然后通过代码msg.target.dispatchMessage(msg)让该msg所绑定的Handler(Message.target)执行dispatchMessage方法以实现对Message的处理。
主线程的Hander使用时不需要调用Looper.prepare()和Looper.loop()是因为在程序入口ActivityThread的main()方法中系统已经自己调用了。
而loop()方法中循环为for (;;) 无条件循环,猜想如果一直循环的话主线程难道不会被卡死吗?如果没有消息的时候结束了循环那MessageQueue中又有了message怎么再次执行Looper.loop()循环方法呢?下面解释上述猜测。
在程序入口ActivityThread中的main()方法部分源码如下:

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

其中thread.attach()方法中,这个Thread是ApplicationThread对象,Binder的服务端,用于接收系统服务AMS发送来的事件,该Binder线程通过Handler将Message发送给主线程,此处涉及到Activity的启动过程,不详细说明。
总结一下,创建 Service、Activity等包括执行其生命周期,最后都是交由 ActivityThread.H 处理,所以 Looper 虽然死循环,但是本质上我们UI的展示、更新,是通过 Handler 来处理,所以并不会造成真正的UI阻塞。
ActivityThread 实际上就是开启了一个消息循环,来执行 Activity、Service 等等的相关操作,一旦这个消息循环停止了,则意味着App进程也结束了。
真正会卡死主线程的操作是在回调方法onCreate/onStart/onResume等操作时间过长,会导致掉帧,甚至发生ANR,looper.loop本身不会导致应用卡死。
所以会阻塞,但是不会卡住,那又会有另一个问题主线程的死循环一直运行是不是特别消耗CPU资源呢?
Android应用程序的主线程在进入消息循环过程前,会在内部创建一个Linux管道(Pipe),这个管道的作用是使得Android应用程序主线程在消息队列为空时可以进入空闲等待状态,这样CPU并不会消耗太多资源在当前这个线程,并且使得当应用程序的消息队列有消息需要处理时唤醒应用程序的主线程。
这里就涉及到Linux pipe/epoll机制,简单说就是在主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,详情见Android消息机制1-Handler(Java层),此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。
总结一下过程:
A. Android应用程序的消息处理机制由消息循环、消息发送和消息处理三个部分组成的。
B. Android应用程序的主线程在进入消息循环过程前,会在内部创建一个Linux管道(Pipe),这个管道的作用是使得Android应用程序主线程在消息队列为空时可以进入空闲等待状态,并且使得当应用程序的消息队列有消息需要处理时唤醒应用程序的主线程。
C. 当往Android应用程序的消息队列中加入新的消息时,会同时往管道中的写端写入内容,通过这种方式就可以唤醒正在等待消息到来的应用程序主线程。
D. 当应用程序主线程在进入空闲等待前,会认为当前线程处理空闲状态,于是就会调用那些已经注册了的IdleHandler接口,使得应用程序有机会在空闲的时候处理一些事情。
参考博客:
https://blog.csdn.net/cjh94520/article/details/71022883
https://www.zhihu.com/question/34652589

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Looper.prepare()和Looper.loop()是Android中消息循环机制的核心方法。Looper.prepare()用于创建当前线程的消息循环对象,而Looper.loop()则用于启动消息循环,使得消息队列中的消息得以被处理。在Android中,UI线程就是一个消息循环线程,通过Looper.prepare()和Looper.loop()的配合,可以实现UI线程的消息循环机制,从而保证UI界面的流畅性和响应性。具体来说,Looper.prepare()会创建一个Looper对象,并将其存储在ThreadLocal中,而Looper.loop()则会不断地从消息队列中取出消息,并将其分发到对应的Handler中进行处理。在消息处理完成后,Looper.loop()会继续等待下一个消息的到来,从而实现消息循环的效果。 ### 回答2: 在Java中,Looper.prepare()和Looper.loop()是与Android消息循环机制相关的两个方法。 首先,Looper.prepare()方法是用来创建当前线程的消息队列Looper对象。每个线程只能有一个Looper对象,用于处理该线程接收到的消息。在调用Looper.prepare()方法后,会创建一个Looper对象,并将其保存在ThreadLocal中,以便该线程其他地方可以直接访问。一般来说,在创建Handler之前,需要先调用Looper.prepare()方法。 其次,Looper.loop()方法是调用当前线程的消息循环机制。一旦调用该方法,程序就会进入一个无限循环的状态,不断地从消息队列中取出消息并处理。在处理完一条消息后,继续取出下一条消息进行处理,以此类推。这个无限循环直到Looper对象调用了quit()方法,才会退出循环。 在Android开发中,通常在主线程中会调用Looper.prepare()和Looper.loop()方法来初始化和启动消息循环,以便接收并处理用户交互事件或其他异步事件。然后通过创建Handler对象,将需要处理的消息发送到消息队列中,Looper.loop()方法会负责从消息队列中轮询消息,并根据消息类型调用相应的Handler处理函数。 总之,Looper.prepare()方法创建当前线程的消息队列,Looper.loop()方法负责启动消息循环并处理队列中的消息,这两个方法共同构成了Java中利用消息队列实现消息循环机制的基础。 ### 回答3: 在Java中,Looper.prepare()和Looper.loop()是Android系统中的主要组件之一——消息循环机制(Message Loop Mechanism)中的关键方法。消息循环机制是Android系统用来实现多线程之间通信的重要工具。 首先,Looper.prepare()的作用是在当前线程中创建一个消息队列(Message Queue)和Looper对象。消息队列用于存储待处理的消息,而Looper对象则用于管理消息队列。每个线程最多只能有一个Looper对象,保证线程与消息队列一一对应。 其次,Looper.loop()的作用是启动消息循环,开始不断地从消息队列中取出消息并依次处理。该方法会一直循环执行,直到调用Looper.quit()方法停止消息循环。 具体来说,当调用Looper.prepare()方法时,会为当前线程创建一个消息队列,并通过ThreadLocal保存Looper对象。然后通过Looper.myLooper()方法可以获取当前线程的Looper对象。接下来,通过Looper.loop()方法启动消息循环,从消息队列中获取消息,并传递给Handler进行处理。当消息队列为空时,Looper.loop()方法会进入休眠状态,等待新的消息进入队列。在消息循环期间,调用Looper.quit()方法可以停止消息循环,并释放相关资源。 通过消息循环机制,可以实现多线程间的异步通信。主线程通常会创建一个消息循环,用于处理UI事件和与用户交互的消息。在子线程中,通过调用Looper.prepare()和Looper.loop()方法,可以为当前线程创建独立的消息队列,从而实现线程间的消息传递和任务调度。 总之,Looper.prepare()和Looper.loop()是Java中实现消息循环机制的关键方法,前者用于创建消息队列和Looper对象,后者用于启动消息循环并处理消息。通过合理地使用消息循环机制,可以实现多线程之间的高效通信和任务调度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值