-1

I have three tasks running within an AsyncTask class. I want to run these tasks in parallel, without making use of three AsyncTask classes. Is this possible? If yes, how could it be done?. Below you can find a code snippet of my AsyncTask class and its doInBackground method.

private class AsyncBenchmarking extends AsyncTask<Void, Void, Integer> {
    @Override
    protected void onPreExecute() {
        lockScreenOrientation();
        animateScreen();

        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {

        firstTaskPerformance = objPrimeNumber.generatePrimeNumbers();
        secondTaskPerformance = objLinpack.linpackBenchmark();
        thirdTaskPerformance = objSuperPi.calculatePi(100000);

        return;
    }
}
lucifer
  • 1
  • 2

3 Answers3

3

The api says :

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

So, for parallel execution :

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}

Hope it helps !

Abhinav Puri
  • 4,254
  • 1
  • 16
  • 28
2

You can use Thread instead.

new Thread((new Runnable() {

        @Override
        public void run() {
            //somecode 1
        }
    }).start();
new Thread(((new Runnable() {

        @Override
        public void run() {
            //somecode 2
        }
    }).start();
new Thread(((new Runnable() {

        @Override
        public void run() {
            //somecode 3
        }
    }).start();
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

Thread should not be manipulated directly. You should use instead ExecutorService class like describe here : https://developer.android.com/reference/java/util/concurrent/ExecutorService.html

If you want to execute three tasks in parallel then set poolSize to 3

Nothing more, nothing less

avianey
  • 5,545
  • 3
  • 37
  • 60