Thread
A thread is a line of code execution within an application. An application can have multiple threads running at the same time. In other words, threads allow an application to behave multitasking. In Java, the class Thread
is a representation of a thread of the Java Virtual Machine or JVM (which does not necessarily correspond to a thread of the host operating system, but this is not the case).
Handlers and Threads
For the difference between Handler
and Thread
, see this question. Note that Handlers
are not Threads
; Handlers
have that name because they serve to deliver messages (a message or Message
is basically the encapsulation of a Runnable
, that is, a chunk of executable code) for threads who stay in loop awaiting the arrival of these code snippets to execute.
For a thread to stay in loop, it is necessary to create a message queue for it calling the methods Looper.prepare()
and Looper.loop()
within itself thread. In the case of thread the system itself already makes these steps, so we have already found it in loop by default.
We used a Handler
when we want a thread secondary perform many messages, or when we want to deliver a message to the thread main. In the latter case we can avoid the use of the Handler
through the method Activity.runOnUiThread()
(if we are in a Activity
), or through a AsyncTask
.
Asynctasks
One AsyncTask
is a class that allows you to execute three code snippets in sequence: the first will be executed by thread leading (thread UI), the second by one thread secondary, and the third again by the thread main. Underneath the plans this is implemented using Threads
and Handlers
.
AsyncTasks
are intended to simplify the implementation of this sequence of steps, which is very common to happen on Android (for example: fire an animation of "loading", perform a task in the background, and then interrupt the animation).
This sequence is made thus, separated into threads and not all in the same thread, because the thread main is reserved to update the screen and can not perform tasks in the background under penalty of losing responsiveness.
No. I want something that exemplifies difference among the three.
– Machado
Handler and thread are different things, can’t compare. Asynctask internally uses an Handler and a thread.
– ramaral
are different things but have a connection and can interact. I think what he wants is the explanation of how and when this happens. Not necessarily compare them.
– Pedro Laini
Exactly, I’m looking to differentiate the three given that they work in the same context.
– Machado