androidmultithreadingkotlinandroid-handler

how to use handler on android concurrently?


I'm reading about threading in android and Kotlin and I found in one tutorial that handler like this example is not working concurrently, and it works one after another but because the processor is too fast we can't notice the difference here is the example

 Handler().postDelayed({println("handler 1")},1000)
 Handler().postDelayed({println("handler 2")},1000)
 Handler().postDelayed({println("handler 3")},1000)

So I asked how handler can work concurrently or in other words in Asynchronous way, like normal threads?


Solution

  • Handler can't work in an asynchronous way in the same thread.

    A handler allows you to send and process Messages and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. The MessageQueue is a queue that has a list of tasks (messages, runnable) that will be executed in a certain thread. 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 executes them as they come out of the message queue. The looper is responsible for keeping the thread alive. It is a kind of worker that serves a MessageQueue for the current thread. Looper loops through a message queue and sends messages to corresponding threads to process.

    When a handler is created, it can get a Looper object in the constructor, which indicates which thread the handler is attached to. So attaching handlers to the different threads can make them Asynchronous. Here you are posting the runnables in same thread MessageQueue with same time delay so it will execute sequentially.

    To know more knowledge about Handler, Thread, Looper, and Message Queue you can read this blog