Difference between AsyncTask and Thread/Runnable
Asked Answered
P

6

62

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

Puissance answered 4/7, 2013 at 16:26 Comment(0)
B
51

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.

Biron answered 4/7, 2013 at 16:28 Comment(8)
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.Bartel
@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.Hoboken
AsyncTask : Response after process completion , Thread : process completion .Seow
ok. so basically both are the same but with different approaches?Puissance
@AlexGittemeier Thanks for Sharing this , I am not an Android guy though !Biron
@GabeSechan executeOnExecutor(...) was added in API 11. Do we have the option to ability to always use this, while still supporting older versions?Bartel
@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.Hoboken
Take note that, merely using Thread or AsyncTask isn't sufficient, when dealing with activity memory leak and configuration changes. #8418385Housman
D
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!

Dillon answered 4/6, 2014 at 3:7 Comment(1)
You can, if you use executeOnExecutor() (which you can do conditionally, so you won't lose compatibility).Schenk
H
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

Harberd answered 30/8, 2017 at 5:21 Comment(0)
S
1

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

Swearword answered 21/8, 2020 at 20:9 Comment(0)
S
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.

Seersucker answered 28/5, 2015 at 9:38 Comment(0)
D
0

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

Detailed answered 6/12, 2018 at 10:12 Comment(1)
try to give a detailed information about your answer. add a bit of code if possible.how to answerStanfield

© 2022 - 2024 — McMap. All rights reserved.