4

I am confused while trying to understand the Processes and Threads concepts in Android. Below I mention a few questions. Maybe those are stupid questions, but please help me answer to answer these questions and clarify my doubts.

1) If I create a thread where will it run? in Main(UI) Thread?

2) If my created thread runs in the background as a worker Thread then what is the use of AsyncTask (I mean how it is better than thread)?

3)Can we create a Thread in AsyncTask?

kandroidj
  • 13,784
  • 5
  • 64
  • 76
Krishna
  • 343
  • 1
  • 2
  • 9

3 Answers3

7
 1. If i create a thread where it will run? in Main(UI) thread/Worker Thread?

it will run in a Worker thread not in the Main Thread.

2.If my created thread runs on worker `Thread` then what is the use of `AsyncTask` (I mean how it is better than thread)?

AsyncTask is used to communicate with the Main Thread..For example you are dowloading File from internet so here you want to update the Download progress in Your Activity..for this AsyncTask better suits. You will update The Ui using onProgressUpdate() method.So you can easily communicate with UI thread.

 3)Can we create a thread in Async task?

Yes you can create it but it is useless because AsyncTask has a doInBackGround()method that already runs in a different Thread so there is no need to create a new Thread inside AsyncTask.

kandroidj
  • 13,784
  • 5
  • 64
  • 76
kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
6
  1. If you are creating a thread in Activity. it will run as a separate thread. By default Activity runs in UI thread.It is also called main thread.
  2. Async task is nothing but a worker thread which is used to run backround operations which will not block the UI thread. eg: downloading a file.
  3. Asynctask itself a separte thread and it has its own life cycle.
Shriram
  • 4,343
  • 8
  • 37
  • 64
1

1) It will run as a worker thread, not on the UI thread.

2) Async Task gives you the possibility to execute certain things before or after the task has finished. Especially useful when having to update UI values after getting data from an internet connection or similar actions. Also works great for progressdialogs. It's a type of class (extends AsyncTask), so there's more structure to it then just starting a thread.

3) Yes, you can. Whether or not this would be very useful to you, is an entirely different question.

SvenT23
  • 667
  • 6
  • 19