Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread ,UI thread, Worker Thread, Async Task

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?

like image 654
Krishna Avatar asked Dec 09 '22 08:12

Krishna


2 Answers

 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.

like image 124
kalyan pvs Avatar answered Dec 11 '22 08:12

kalyan pvs


  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.
like image 21
Shriram Avatar answered Dec 11 '22 10:12

Shriram