Updated 1 April 2019
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.
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Create Thread by extends Thread class class Task extends Thread { @Override public void run() { // Perform Long Running Task super.run(); } } // Create Thread by implement Runnable class class DownloadTask implements Runnable { @Override public void run() { // Perform Long Running Task } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class DownloadTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... strings) { return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var service = ThreadPoolExecutor( Runtime.getRuntime().availableProcessors(),/* Here we can get Device available Processors*/ 50,/* Defined Queue size*/ 1,/* Timeout in numberic */ TimeUnit.SECONDS,/* Timeout unit */ LinkedBlockingQueue<Runnable>()) /* Defined LinkedBlockingQueue of Runnable here */ service?.execute(object : Runnable { override fun run() { // Perform Long running operation } }) |
I hope you have got some idea where to use Threads, AsynckTask and ThreadPool.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.