Start a Project

Understanding Multi-threading in Android

Why create a separate thread?

The thread is a process which executes the sequence of instruction. In Android, if there is some task taking more than 5sec it will cause ANR (Application Not Responding) error. To avoid these cases we need to create a separate thread. In Android, there is UI thread which performs entire UI operation that’s mean we cannot perform any UI update on the background thread.

So how can we update UI from a Background thread?

Android introduce Asynctask for such cases we can update UI component in Asynctask and perform the long-running operation at the same time. In Asynctask there are 3 methods onPreExecute(), onBackground() and onPostExecute(). We can perform UI component related operation on onPostExecute() method.

How many threads we can create in Android?

There is no specific limit to create a thread in android we can create as many threads we need to perform background operations. But creating too many threads can cause deadlock if we are unable to manage them. Thread pool is a better approach instead of creating separate threads.

Let’s now discuss when we have to create a Thread, Asynctask, and ThreadPool in android to perform background task. In Android, there are many options to execute background operations.

 

I hope you have got some idea where to use Threads, AsynckTask and ThreadPool.

Exit mobile version