155

In UI, to perform some background work, I used a separate Thread. But as suggested by others, I am now using AsyncTask.

What is the main difference between a Thread and an AsyncTask?

In which scenario, should I use a Thread or an AsyncTask?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
Ram
  • 2,532
  • 4
  • 22
  • 25
  • 5
    See http://stackoverflow.com/a/9800870/2617699 – JavaDM Aug 28 '13 at 05:45
  • @webaldo.at I reffered this,here they given enter description and difference between Asynctask and Thread.I want to know which case for example network connection,file read for that what i use?. – Ram Aug 28 '13 at 05:56
  • Shortened: Thread -> No Access to the UI-Thread || Asynctask -> Conditional Access to the UI-Thread – JavaDM Aug 28 '13 at 06:02
  • for background task IntentService is another nice option. – Chen Jul 02 '15 at 20:24
  • 1
    Possible duplicate of [Handler vs AsyncTask vs Thread](http://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread) – Ciro Santilli OurBigBook.com Feb 05 '16 at 14:26

6 Answers6

166

For long-running or CPU-intensive tasks, there are basically two ways to do this: Java threads, and Android's native AsyncTask.

Neither one is necessarily better than the other, but knowing when to use each call is essential to leveraging the system's performance to your benefit.

Use AsyncTask for:

  1. Simple network operations which do not require downloading a lot of data
  2. Disk-bound tasks that might take more than a few milliseconds

Use Java threads for:

  1. Network operations which involve moderate to large amounts of data (either uploading or downloading)
  2. High-CPU tasks which need to be run in the background
  3. Any task where you want to control the CPU usage relative to the GUI thread

And there are lot of good resources over internet which may help you:

http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

ividito
  • 321
  • 3
  • 14
Mohit
  • 2,940
  • 2
  • 24
  • 32
  • May I ask why the download data amount is an issue? – Yeung Jan 02 '14 at 04:18
  • 2
    @Yeung Seems like you need insight about Async Task! Look, larger the data amount then clearly larger the time taken to complete the same operation. Therefore it's not a good practice to do long running process using Async Task due to following reasons : 1. Async Task is poorly tied to Activity life cycle. 2. They create meomory leaks. – Mohit Jan 02 '14 at 12:37
  • 3
    Have a look at this: http://stackoverflow.com/questions/12797550/android-asynctask-for-long-running-operations?rq=1 – Mohit Jan 02 '14 at 12:39
  • Thank you. I understand the risk now. – Yeung Jan 03 '14 at 03:22
  • 1
    @Impasse @Yeung IMO amount of data is not a problem, the key problem with the network operations it the time of the operation. Even downloading a few bytes may take a long time, when the server is busy, unreachable (timeout) etc. A fix could be to use `AsyncTask` with own scheduler. – xmedeko Jun 17 '16 at 07:55
  • @xmedeko he asked for this use case, so answered accordingly. and in my comments i had specifically mentioned that performing long running processes (which covers all of your use cases) is not a good practice. – Mohit Jun 21 '16 at 05:11
  • @Mohit There is no difference what to use Thread or AsyncTask from the point of memory leaks or activity lifecycle. Both approaches can be implemented correctly. The single argument is to not use AsyncTask for long-term operations is that it has common internal query. Though it can be resolved by custom Executor configuring. – Vladimir Ryhlitskiy Mar 05 '19 at 07:56
48

If you use Java threads you have to handle the following requirements in your own code:

Synchronization with the main thread if you post back results to the user interface

No default for canceling the thread

No default thread pooling

No default for handling configuration changes in Android

T_V
  • 17,440
  • 6
  • 36
  • 48
  • 4
    this is actually more elucidating because it tackles reasons why not to use simple Threads. From the top of my mind, anything that needs to be tied to Activity/Service lifecycle should use AsyncTask instead, even though you need to manually "gracefully degrade" resources inside the task, at least you don't end up with the task hanging when activity is killed. – leRobot Feb 24 '15 at 18:33
34

Thread

  • Long task in general
  • Invoke by thread.start() method
  • Triggered from any thread
  • Runs on its own thread
  • Manual thread management/code may become difficult to read

AsyncTask

  • Small task having to communicate with main thread
  • Invoke by excute() method
  • Triggered from main thread
  • Runs on worker thread
  • Must be executed and created from the main thread
Saurabh
  • 434
  • 1
  • 4
  • 12
Umang Kothari
  • 3,674
  • 27
  • 36
  • I couldn't understand the `Runs on its own thread` vs `Runs on worker thread`? what is the difference between the Own thread and the worker thread? – imany apk Oct 06 '20 at 05:47
14

Thread

A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.

One is providing a new class that extends Thread and overriding its run() method. The other is providing a new Thread instance with a Runnable object during its creation. A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.

A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.

If you use Java threads then you need to handle the following requirements in your own code:

Synchronization with the main thread if you post back results to the user interface No default for canceling the thread No default thread pooling No default for handling configuration changes in Android

AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

AsyncTask will go through the following 4 stages:

onPreExecute()

Invoked on the UI thread before the task is executed

doInbackground(Params..)

Invoked on the background thread immediately after onPreExecute() finishes executing.

onProgressUpdate(Progress..)

Invoked on the UI thread after a call to publishProgress(Progress...).

onPostExecute(Result)

Invoked on the UI thread after the background computation finishes.

Why should you use AsyncTask?

Easy to use for a UI Thread. (So, use it when the caller thread is a UI thread).

No need to manipulate Handlers.

For further information visit Here

Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
6

Thread:

Thread should be used to separate long running operations from main thread so that performance is improved. But it can't be cancelled elegantly and it can't handle configuration changes of Android. You can't update UI from Thread.

AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask, you can update UI unlike java Thread. But many long running tasks will choke the performance.

You have few more alternatives to both of them.

HandlerThread/ Handler and ThreadPoolExecutor

Refer to below post for more details:

Handler vs AsyncTask vs Thread

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

If you have longer tasks which should work concurrently to leverage the CPU cores and shorten time latency, you should absolutely use Multithreading or a Thread:

  • You can initialize the thread form the Background Thread or (initialization can be possible as Inner Thread) unlike AsyncTask.
  • You don't need to inherit parent class and override methods (More Clean and Precise).
  • You can manage Concurrency yourself with multithreading, just read about Volatile and Atomicity.
  • For publishing on UI, you can use synchronized thread and notify UiThread using UIhandler.
Nadin Martini
  • 193
  • 2
  • 4
  • 13