Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Difference between Thread and AsyncTask?

In my app i have buttons, when clicked will query the database and show result on screen. The query action will normally take 1 ~ 3 sec. These buttons will be clicked very often.

I've implemented this action on both AsyncTask and Thread but see very little different.

However in the long term, especially when the buttons are clicked many times, which will be more beneficial, in terms of resources (CPU, memory) ?

like image 969
Tran Ngu Dang Avatar asked Mar 07 '15 10:03

Tran Ngu Dang


People also ask

What is the difference between AsyncTask and thread runnable?

AsyncTask : Response after process completion , Thread : process completion .

What is the difference between handler vs AsyncTask vs thread?

AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services. Later you can interact with the UI. Thread however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTask .

Is AsyncTask a thread?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

How many threads are there in AsyncTask in Android?

In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).


1 Answers

When you use a Thread, you have to update the result on the main thread using the runOnUiThread() method, while an AsyncTask has the onPostExecute() method which automatically executes on the main thread after doInBackground() returns.

While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread, it may not always be as simple as calling runOnUiThread(); it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask and keep Thread for more specialized situations.

like image 95
Y.S Avatar answered Sep 19 '22 12:09

Y.S