在主线程上创建的 Android 视图、activity/windows 和处理程序是否有单独的消息队列?
Do Android views, activity/windows and handlers created on main thread have separate message queues?
我的理解是,由于只有一个 UI 线程 - 将有一个 UI 消息队列。不管我们使用什么方法
Handler(Looper.getMainLooper()).post()
View.post()
View.getHandler().post()
Activity.runOnUiThread()
这些可运行对象被添加到一个 UI 消息队列并串行执行。
如果我错了,并且我通过代码创建的每个视图和每个处理程序都有多个消息队列(将它们全部附加到 UI 线程),UI 线程如何决定执行顺序和哪个队列优先?
只有一个MessageQueue
。尽管可能有多个 Looper
,每个线程一个。
MessageQueue
在每次轮询时同步。
你可以看到Looper.java
的实现:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
然后whenever queue is looped它可能会阻塞:
Message msg = queue.next(); // might block
并且implementation of MessageQueue#next()
采用synchronized
方法。
注意,代码中的注释不是我做的
我的理解是,由于只有一个 UI 线程 - 将有一个 UI 消息队列。不管我们使用什么方法
Handler(Looper.getMainLooper()).post()
View.post()
View.getHandler().post()
Activity.runOnUiThread()
这些可运行对象被添加到一个 UI 消息队列并串行执行。
如果我错了,并且我通过代码创建的每个视图和每个处理程序都有多个消息队列(将它们全部附加到 UI 线程),UI 线程如何决定执行顺序和哪个队列优先?
只有一个MessageQueue
。尽管可能有多个 Looper
,每个线程一个。
MessageQueue
在每次轮询时同步。
你可以看到Looper.java
的实现:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
然后whenever queue is looped它可能会阻塞:
Message msg = queue.next(); // might block
并且implementation of MessageQueue#next()
采用synchronized
方法。
注意,代码中的注释不是我做的