Threads Flashcards

1
Q

What is a Looper?

A

Threads in android work in a way like they start, execute their code block written in run() method and then get destroyed. But in android, the main thread is responsible to run UI, so the question is how does the main thread keep on running.

Here comes Looper in the picture. Looper provides Thread an ability to keep on running in a loop and associates a MessageQueue for the thread on which this Looper object is created. When a Message or Runnable is posted, Looper executes those on its associated thread.

Note that, only one Looper can be created per Thread. It implies one MessageQueue per thread also. But multiple Handler can be created for a single Looper.

Looper.prepare(), Looper.quite(), Looper.loop() are the functions used to start, end and keep on loop the thread respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is MessageQueue?

A

Looper provides the ability to run in a loop for threads with its own MessageQueue. MessageQueue is a queue that has tasks called messages which should be processed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a Handler?

A

The handler provides a way to communicate with Looper. Handler sends Runnable or Message object on Looper, providing a way to execute code on a particular thread from another thread.

Each Handler always has a Looper object associated with it. Whenever we post a Runnable or send a Message on a Handler, it executes on the Thread associated with the Handler’s Looper.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly