user5162677
user5162677

Reputation:

Android Studio is not running AsyncTasks at the same time. Why?

Suppose I have 2 AsyncTasks A and B.

Let A be:

public class A extends AsyncTask<Void, Void, Void> {

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

        int a = 1;
        while(a < 10){
            System.out.println(a);
            for(int i = 0; i < 400000; i++){
                //empty loop, just to spend time
            }
            a = a+2;
        }          
    }
}

Let B be:

public class B extends AsyncTask<Void, Void, Void> {

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

        int a = 2;
        while(a < 10){
            System.out.println(a);
            for(int i = 0; i < 400000; i++){
                //empty loop, just to spend time
            }
            a = a+2;
        }          
    }
}

I call both of them at my MainActivity like this:

...
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new A().execute();
    new B().execute();
}

I expected the result to be some kind of merge (not perfect but somehow merged) between odds and evens, but I'm getting the whole result of A and after the whole result of B, like this:

1
3
5
7
9
2
4
6
8

Can anyone tell me if this is normal?

Is it possible to have multiple AsyncTasks running at the same time? (I think it is, because I know they are like threads)

If it is, what did I do wrong?

Thank you guys.

Upvotes: 1

Views: 586

Answers (2)

d0nut
d0nut

Reputation: 2834

Actually, no, that's not how AsyncTasks work. Assuming you're testing this on a device past Honeycomb, your asynctasks will queue up like they are in your example.

AsyncTask

Read the section titled "Order of Execution"

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.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Upvotes: 0

rslgp
rslgp

Reputation: 26

Android two AsyncTasks serially or parallel execution? - The second is freezing but the result is ok

You can opt into parallel execution by replacing execute() with executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR).

https://www.youtube.com/watch?v=HNcE6MLnuIw

Upvotes: 1

Related Questions