Does AsyncTask works simultaneously?

好久不见. 提交于 2019-12-05 16:44:18
Hemant Parmar

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
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!