Addressing your additional question:
You said "In Android we have Handler#post(Runnable) method to post some code to the main thread from another"
It is not exactly correct. You can 'post some code' from any thread A to any thread B provided that thread B is initialized as a Looper
and the thread A has a reference to a Handler
for the target thread B.
It is very convenient when you need to do something on the UI thread because the UI thread already has a Looper
and you can retrieve it from nearly everywhere. The static method Looper.getMainLooper
is a way to get a Looper
for the main thread. If you initialize a Handler
with this Looper
you can post a Runnable
or send a Message
to it (though if you post Runnable
it also gets wrapped into a Message
) and it will be executed on the UI thread.
Looper
, as the name hints, is basically running a non-terminating loop for a thread. The Looper
has an associated MessageQueue
which it constantly checks for new Messages.
Via the Handler
initialized with a Looper
you can enqueue Messages
on this thread. The Messages
are processed in a sequential order, depending on the when
field of a Message
.
Here's a basic implementation of a Looper thread:
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();
}
}
I suggest you read the Chapter 5 of Meike G.B. Android Concurrency. It will give you a comprehensive insight into the Looper/Handler framework. It is also great to browse the source code while you are reading, it is rather simple and self-explanatory.