Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between AsyncTask and Thread/Runnable

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

like image 930
kevoroid Avatar asked Jul 04 '13 16:07

kevoroid


1 Answers

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.

like image 172
AllTooSir Avatar answered Sep 23 '22 01:09

AllTooSir