How Android inter thread communication works?

Inter thread communication : means passing some data between threads.

Every thread internally will have 2 components: Looper & Message queue.


Message Queue : is to store incoming messages


Looper : will keep checking message queue to respond to those messages. Without Looper, it is not possible to achieve Inter thread communication.


Only Handler Threads will have loopers.

Normal Java threads will also have loopers but they will be in the passive mode. (Since looper is passive it cannot check message queue for new incoming message).
Since your looper is not active in java threads so they cannot handle inter thread communication.                           
You can enable the looper by calling looper.prepare().

So, Inter thread communication is possible through only Handler Threads. Because Handler threads allows message passing mechanism through loopers.

There is one more technique to have Inter thread communication.
Share some data in some common storage, and allow both the threads to access that data by using some synchronization mechanism like wait, notify.
This is possible with normal java threads also.

No comments:

Post a Comment