Search code examples
javaandroidandroid-asynctaskandroid-handlerjava-threads

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) ?


Solution

  • 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.