Petros Mastrantonas
Petros Mastrantonas

Reputation: 1046

Calling a bunch of AsyncTask, is there a way of knowing when they are all finished to show a message?

So what I am doing is, I have a loop and I call a AsyncTask inside my loop, so there might be a bunch of them. From my understanding is, after the loop is done I can't just display a message that everything is complete, because the message will appear before the AsyncTasks are done, since thats kinda the point of asynchronous threading.

If I would had just one AsyncTask it would be a nobrainer, I would put my code to display a message into onPostExecute() but now I have many of them.

So is there a way of knowing when all the AsyckTast threads are all finished so I can show my message?

Thanks for you answer in return, as you might have guess, I am kinda new to Java.

Upvotes: 1

Views: 87

Answers (1)

tibtof
tibtof

Reputation: 7957

Try with a static Integer that increments for every AsyncTask created and in onPostExecute() decrement it. When it reaches 0 all your task will be finished.

E.g.: when task is created:

 synchronized(staticInt) {
    //create AsyncTask
    ++staticInt;
 }

And when it finishes:

 protected void onPostExecute(Object result) {
     synchronized(staticInt) {
        --staticInt;
        if (staticInt == 0) {
           //show message
        }
     }
 }

As @James suggested, you could also use it to control the maximum number of AsyncTask executing at a certain time:

 while (staticInt >= MAX_NUMBER_OF_THREADS) {
     //wait
 }

 synchronized(staticInt) {
    //create AsyncTask
    ++staticInt;
 }

It can be improved with a wait-notify approach.

Upvotes: 1

Related Questions