androidmultithreadingmessagemessage-queue

Difference between event queue and message queue


I was just seeing the documentation of three methods which can be used to execute a piece of code in the UI thread while we are working in a worker thread. The methods are:

  1. public final void runOnUIThread(Runnable action) - Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread

  2. public boolean post(Runnable action) - Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

  3. public boolean postDelayed(Runnable action, long delayMillis) - Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the user interface thread.

The first one posts the Runnable to the event queue of the UI thread, while the other two add the Runnable to the message queue. Please tell me the difference between the two?

My web search tell me that an event queue is simply a queue of events waiting to be executed by the thread. I am not clear about the message queue. MessageQueue is some class as well, is this related to that?

Thank you in advance.


Solution

  • I think the two are synonymous. Events are indicated to the system using messages.

    The real difference between the two methods is that one appends it to the queue immediately while the other delays it by the specified amount.

    EDIT: More on messages

    Messages are a way of communication between independent threads. In a way, it's a lot like the communication that takes place when you pull up a website in your browser: You send a message to the server detailing what exactly it is you want (GET www.stackoverflow.com, I will accept the following character encoding, do not track me, blablabla), which makes the server as the recipient of the message do something (retrieve content from the database, render the page, etc) and communicate the results of this back to you via a message.

    How it works is like this: The thread has a Looper attached to it. All it does is run forever in a continuous loop, on each iteration checking whether there are any messages in its message queue. If there aren't, it goes to the next cycle. If there are, it retrieves the first message to deal with it.

    However, the looper itself doesn't know what any of the messages mean - it's just there for looping. Neither does the thread, which just provides the infrastructure for the looper to run in. What the looper does know, however, is who to go to for handling the message: One of its Handlers. It passes the message to the handler, which can now go and do whatever it is that it needs to do to handle the message.