Thread or Asynctask? When and which one should I use?

Asked

Viewed 907 times

9

When it is recommended to use threads?
At what point it is advisable to use the AsyncTask?
I would like to know what to use and when to use it.

1 answer

9


Asynctask is a class that facilitates the use of threads in conjunction with the Main Thread.

Asynctask creates an internal Thread to execute the code declared in the method doInBackground() and a Handler to run on the Main Thread the code declared in the method onPostExecute().

It also provides a way to execute code in Main Thread while the code in background is executed using publishProgress() to invoke the method onProgressUpdate().

So use Asynctask to perform operations that last a few seconds(1) and whose result should be used by Main Thread.

Asynctask must be created and executed in the Main Thread so use the class Thread when this is not the case, you have to perform long or short operations when you do not need to access Main Thread.

Behold here other alternatives such as classes Executioner, Threadpoolexecutor and Futuretask.

(1)
This restriction shall apply only if Asynctask is executed by the method execute(). This method executes the Tasks sequentially, in a single thread, causing the Task next boot only after completion of previous.
Restriction can be avoided using the method executeOnExecutor(), passed to it an executor, usually Asynctask.THREAD_POOL_EXECUTOR, in order to use a pool of threads to perform the tasks in parallel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.