61

I have question which puzzles me.

Imagine I wanna do something in another thread, like fetching GPS/Location stuff, which as recommended in the SDK documents, must use a background thread.

So here is the question: What's the difference between

  1. Creating a Thread in background via AsyncTask AND

  2. Creating Thread thread1 = new Thread(new Runnable() ... and implementing run()?

kevoroid
  • 5,052
  • 5
  • 34
  • 43

6 Answers6

49

AsyncTask is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

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.

The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Also if I quote from this blog:

if you need SIMPLE coding use AsyncTask and if you need SPEED use traditional java Thread.

Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Do note though, that depending on the version of android your code runs on, there can only be one AsyncTask running at any one time. – Alex Gittemeier Jul 04 '13 at 16:30
  • 1
    @AlexGittemeier Even on those versions you can tell it to run more by using executeOnExecutor and telling it to use a pool, rather than just calling execute. – Gabe Sechan Jul 04 '13 at 16:31
  • 1
    AsyncTask : Response after process completion , Thread : process completion . – Tushar Pandey Jul 04 '13 at 16:32
  • 2
    ok. so basically both are the same but with different approaches? – kevoroid Jul 04 '13 at 16:32
  • @AlexGittemeier Thanks for Sharing this , I am not an Android guy though ! – AllTooSir Jul 04 '13 at 16:33
  • @GabeSechan executeOnExecutor(...) was added in API 11. Do we have the option to ability to always use this, while still supporting older versions? – Alex Gittemeier Jul 04 '13 at 16:34
  • 1
    @AlexGittemeier Before version 11, it allowed multiple async tasks by default. So basically check the version, if its below 11 just call execute, if its above 11 call executeOnExecutor(). Then the only ones that won't work are pre-2.0, which at this point I wouldn't worry about. – Gabe Sechan Jul 04 '13 at 18:41
  • Take note that, merely using Thread or AsyncTask isn't sufficient, when dealing with activity memory leak and configuration changes. http://stackoverflow.com/questions/8417885/android-fragments-retaining-an-asynctask-during-screen-rotation-or-configuratio?rq=1 – Cheok Yan Cheng Jun 04 '14 at 04:16
2

Also take in count that starting on Android v4.04, you can't have more than one AsyncTasks at a time, unless you lose compatibility with lower versions. Be aware!

RBT
  • 24,161
  • 21
  • 159
  • 240
Lorenzo
  • 31
  • 1
  • 6
    You can, if you use `executeOnExecutor()` (which you can do conditionally, so you won't lose compatibility). – matiash Jun 04 '14 at 03:26
2

Key differences:

  1. AsyncTask is an asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. It can't be done with normal thread unless you use Handler on UI Thread and post a message OR directly change attribute of an object by implementing proper synchronization.

  2. As recommended by developer guide regarding Thread performance,

    There are a few important performance aspects to keep in mind. First, by default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. For this reason, we suggest that you only use AsyncTask to handle work items shorter than 5ms in duration..

    But normal Thread can be used for long running tasks.

Plain java Threads are not much useful for Android unlike HandlerThread, which has been provided by Android framework.

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

Refer to below post to know more details:

Handler vs AsyncTask vs Thread

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
1

AsyncTask deprecated with api level 30. Using thread/runnable is convenient

E.Oguz
  • 11
  • 1
0

One obvious drawback for AsyncTask class is that after Android 3.0 asynctasks are executed according to the sequence of the start time. that is tasks are executed one by one, unless you execute the task by calling 'executeOnExecutor(Executors.newCachedThreadPool())'. this method would create your own thread pool.

Yuan
  • 135
  • 1
  • 9
0

Better to use the new Job Scheduler in the support library.

  • 1
    try to give a detailed information about your answer. add a bit of code if possible.[how to answer](https://stackoverflow.com/help/how-to-answer) – Agilanbu Dec 06 '18 at 10:31