Executing Multiple AsyncTasks at same time

AsyncTask is nothing but executing a long running process such as network call in another thread without disturbing / blocking the running main thread to avoid UI glitches. Since providing a responsive UI is the main objective of main thread. We all aware of creating and executing an asynctask, but may not be aware of running multiple asynctasks at same time for different purposes. Let me discuss this in detail with an example.

Points to be noted from the video.
1. An app with four horizontal progress bars. Let us name them A,B & C,D a separate asynctask is provided to increase the progress of each progress bar.
2. A, B runs serially one after another get finished (normal).
3. C, D runs parallel (both at same time)

AsyncTask class

class asynCTasks extends AsyncTask<ProgressBar, Integer, Void> {
private ProgressBar pBarIs;

@Override
protected Void doInBackground(ProgressBar… params) {
this.pBarIs = params[0];
for (int inteGerIs = 0; inteGerIs < 100; inteGerIs++) {
publishProgress(inteGerIs);

try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}

@Override
protected void onProgressUpdate(Integer… values) {
super.onProgressUpdate(values);
pBarIs.setProgress(values[0]);
}
}

onResume() is shown below

@Override
protected void onResume() {
super.onResume();
aTask1 = new asynCTasks();
aTask1.execute(pBar1);
aTask2 = new asynCTasks();
aTask2.execute(pBar2);
// parallel execution
aTask3 = new asynCTasks();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
aTask3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pBar3);
else
aTask3.execute(pBar3);
aTask4 = new asynCTasks();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
aTask4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pBar4);
else
aTask4.execute(pBar4);
}

Note “executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);” it executes more than one asynctasks in parallel.

Get source code from github.

Enjoy! Happy Coding!

--

--