When is it recommended to use threads
?
At what time is it advisable to use AsyncTask
?
I would like to know what to use and what time it is needed.
When is it recommended to use threads
?
At what time is it advisable to use AsyncTask
?
I would like to know what to use and what time it is needed.
AsyncTask is a class that facilitates the use of threads in conjunction with the Main Thread .
AsyncTask internally creates a Thread to run the declared code in thedoInBackground()
method and a handler to run on the Main Thread the code declared in the onPostExecute()
method.
It also provides a way to execute code in the Main Thread while the code in background is executed, using publishProgress()
to invoke the onProgressUpdate()
method.
So, use AsyncTask to perform operations that last a few seconds (1) and whose result should be used by Main Thread .
AsyncTask has to be created and executed on the Main Thread so use the Thread class when this is not the case, you have to execute the Thread long or short operations when you do not need to access the Main Thread .See here other alternatives like the Executor classes in>, ThreadPoolExecutor and FutureTask .
This subclause only applies if AsyncTask is run through the execute () . This method executes Tasks sequentially in a single thread , causing the next Task only to boot after the previous one has finished. > Restriction can be avoided by using the executeOnExecutor () , passed to it an executor, usually AsyncTask.THREAD_POOL_EXECUTOR, in order to use a pool of threads to execute the tasks in parallel .