这是冗余使用处理程序的示例吗?

Is this an example of redundant use of Handlers?

如果使用相同的 Looper,那么拥有多个 Handler 有什么意义吗?

例如:

private Handler firstHandler = new Handler(Looper.getMainLooper());
private Handler secondHandler = new Handler(Looper.getMainLooper());
firstHandler.post(...);
secondHandler.post(...);

...他们都post到主线程,有第二个没有意义吗?

谢谢。

Is this an example of redundant use of Handlers?

是的。

转自Docs:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

这些处理程序正在向同一个 MessageQueue 发送消息,所以无论如何第二个将在第一个完成后 运行,这意味着它是多余的。

此外,Handler 与默认创建它的 Thread 相关联。因此,如果 Handler 是在 main thread 上创建的,则您不必指定 Looper。

是的,两个处理程序都指向同一个 "MessageQueue"。更多信息可以从以下link:

获得

What is the purpose of Looper and how to use it?