How to ensure that all threads have run?

Asked

Viewed 189 times

0

How can I guarantee that the get method of a Futuretask will only be called when all threads have already run?

I have this method :

for (int j = 0; j < threadNum; j++) {
        FutureTask<Integer> futureTask = taskList.get(j);
        if(!taskList.get(j).isDone()){
            System.out.println("Não terminou: ");
        }
        amount += futureTask.get();

    }

I should make an infinite loop before this is to ensure that it will only get here when all threads finish running or there is another way to do this?

  • The method futureTask.get() wait for thread to finish to get its value. It’s like a "wait and then get".

1 answer

1


Using Futuretask you don’t need a loop to check if you’re done. You also don’t need a specific method to wait to finish. The method itself get does both - waits to finish and then gets the computed value.

Your code would look something like this:

for (FutureTask<Integer> futureTask : taskList) {
    amount += futureTask.get();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.