Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a number of threads to complete?

What is a way to simply wait for all threaded process to finish? For example, let's say I have:

public class DoSomethingInAThread implements Runnable{      public static void main(String[] args) {         for (int n=0; n<1000; n++) {             Thread t = new Thread(new DoSomethingInAThread());             t.start();         }         // wait for all threads' run() methods to complete before continuing     }      public void run() {         // do something here     }   } 

How do I alter this so the main() method pauses at the comment until all threads' run() methods exit? Thanks!

like image 220
DivideByHero Avatar asked Aug 09 '09 20:08

DivideByHero


People also ask

How do you make a thread wait for some time?

In between, we have also put the main thread to sleep by using TimeUnit. sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.

Does Java wait for all threads to finish?

Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.

How do you wait for a runnable to finish?

Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .


2 Answers

You put all threads in an array, start them all, and then have a loop

for(i = 0; i < threads.length; i++)   threads[i].join(); 

Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that's not a problem: when the loop exits, all threads are completed.

like image 130
Martin v. Löwis Avatar answered Nov 10 '22 00:11

Martin v. Löwis


One way would be to make a List of Threads, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call join() on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.

A better approach is to use an ExecutorService and its associated methods:

List<Callable> callables = ... // assemble list of Callables here                                // Like Runnable but can return a value ExecutorService execSvc = Executors.newCachedThreadPool(); List<Future<?>> results = execSvc.invokeAll(callables); // Note: You may not care about the return values, in which case don't //       bother saving them 

Using an ExecutorService (and all of the new stuff from Java 5's concurrency utilities) is incredibly flexible, and the above example barely even scratches the surface.

like image 42
Adam Batkin Avatar answered Nov 10 '22 00:11

Adam Batkin