2
new Thread(new Runnable(){

}).run();

vs

new AsyncTask().execute();

I was under the impression they were the same thing, both start a new worker thread but is that not the case?

The reason I ask is because if I try to do any sort of network connection using new Thread() I get a NetworkOnMainThreadException but when I put that same code in an async task I do not get that.

also another example of this difference is using google maps api v2 where all plots/show/hides have to be done on the main thread but if I use new Thread() to hide/show markers the appear fine but if I try to show/hide in an async task I get an exception saying it needs to be done on the main thread.

does new Thread() really not start a worker thread??

EDIT

not sure why this was closed since the links provided I have read and did not answer my question and mentions nothing about using run() vs start() which does answer my question

tyczj
  • 71,600
  • 54
  • 194
  • 296

3 Answers3

6

If you call run() instead of start() it runs on the thread from which it was invoked. If you call start(), then it creates a new thread. That's why you get the error, because you call .run()

NickT
  • 23,844
  • 11
  • 78
  • 121
0

Basically both are equivalent, but AsyncTask is more simple and good approach in android in terms of integration with GUI.

In case of AsyncTask you can download data from server in doInBackground() in this method and update the GUI in postExecute().

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.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
0

NetworkOnMainThreadException exception occurs because you are making a network call on the main UI thread.

If you use AsyncTask you can get rid of that exception. From the documentation 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.

http://developer.android.com/reference/android/os/AsyncTask.html.

http://android-developers.blogspot.in/2009/05/painless-threading.html. The article on the link has a good explanation on the topic.

An alternative to AsyncTask is RoboSpice.https://github.com/octo-online/robospice.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256