Does AsyncTask works simultaneously?

2019-05-07 20:15发布

问题:

Does AsyncTask works simultaneously or first come first served manner? .

For example i've 3 AsyncTasks that have same interface class and same listener functions. Executing 3 AsyncTasks at same time. Which response from AsyncTasks will shows in listener function?

Doubts:

1. Does AsyncTasks run parallel or first come first served manner? 2. If AsyncTasks run parallel manner how to handle same listener function for all AsyncTasks?

Nb: Doubt 2 is because first response recieving while doing multiple requests at same time without using AsyncTask. (Web Api response).

Thanks in advance.

回答1:

For multiple request you can use ThreadPoolExecutor

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    new callApi().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, location);
} else {
    new callApi().execute(location);
}

Thread Pool Pattern

AsyncTask uses a thread pool pattern for running the stuff from doInBackground()

The Thread pool Pattern is where number of Threads are created to perform a number of Tasks. It is basically a container where multiple threads come in a queue for different task.

For Example:

public class MultipleAsyncTask extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        runMultipleAsyncTask(); // Start Async Task
    }
    private void runMultipleAsyncTask() // Run Multiple Async Task
    {
        FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
        if(AppUtil.isCurrentVersionHoneycombAndAbove()) // Above Api Level 13
        {
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        else // Below Api Level 13
        {
            asyncTask.execute();
        }
        SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
        if(AppUtil.isCurrentVersionHoneycombAndAbove())// Above Api Level 13
        {
            asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        else // Below Api Level 13
        {
            asyncTask2.execute();
        }
    }
    //Start First Async Task:
    private class FirstAsyncTask extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPreExecute()
        {
            Log.i("AsyncTask" ,"FirstOnPreExecute()");
        }
        @Override
        protected Void doInBackground(Void... params)
        {
            for(int index = 0; index < 50; index++)
            {
                Log.i("AsyncTask" ,"FirstAsyncTask");
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException exception)
                {
                    exception.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            Log.d("AsyncTask" ,"FirstonPostExecute()");
        }
    }
    //Start Second Async Task:
    private class SecondAsyncTask extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPreExecute()
        {
            Log.i("AsyncTask" ,"SecondOnPreExecute()");
        }
        @Override
        protected Void doInBackground(Void... params)
        {
            for(int index = 0; index < 50; index++)
            {
                Log.d("AsyncTask" ,"SecondAsyncTask");
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException exception)
                {
                    exception.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            Log.d("AsyncTask" ,"SecondOnPostExecute()");
        }
    }
}

Output:

FirstOnPreExecute()
SecondOnPreExecute()
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstAsyncTask
SecondAsyncTask
FirstonPostExecute()
SecondOnPostExecute()

Same asyncTask for different functions like api requests:

boolean flag;
    @Override
    protected String doInBackground (String... params) {
        flag= params[0].endsWith("/repos");
        //other statements
    }

Now in your onPostExecute:

if(flag){
    //parse one way
} else {
    //parse another way
}


回答2:

I agree with the answer given by Hemant Parmar, but there are some more things to know that onPreExecute() of every AsyncTask executes in first come first serve manner after that doInBackground() method of every AsyncTask runs simultaneously.

So if you are executing

new FirstAsyncTask().execute();

new SecondAsyncTask().execute();

Then onPreExecute() of FirstAsyncTask() will complete its execution and will start the doInBackground() of FirstAsyncTask() which will be executing in background, now SecondAsyncTask() will execute its onPreExecute and after completion it will too execute doInBackground() of SecondAsyncTask(). Now both doInBackground() of fisrt and second async task will run simultaneously.