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!
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.
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.
Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .
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.
One way would be to make a List
of Thread
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With