Waiting on multiple threads to complete in Java
Just join them one by one:
for (Thread thread : threads) {
thread.join();
}
(You'll need to do something with InterruptedException
, and you may well want to provide a time-out in case things go wrong, but that's the basic idea...)
Java execute multiple Threads and wait for completion
You may use a CountDownLatch
in addition to the barrier. Pass the CountDownLatch
to each of the thread, once the firmware update is completed, just call the count-down on the latch. In your main thread, after starting all the threads, you may wait by calling latch.await
and it will wail till all the other threads finish. You may find a sample here.
You can even use a CountDownLatch
with 1 as the count for the starting gun in your case, which precludes the use of the CyclicBarrier
.
Java Multithreading wait for threads to finish
Add calls to join()
at the end of run. the join()
method waits for a thread to finish.
try
{
one.join();
two.join();
three.join();
four.join();
}
catch (InterruptedException e)
{
System.out.println("Interrupt Occurred");
e.printStackTrace();
}
And if you want to ignore interrupts (probably should at least figure out why it was interrupted but this will work)
boolean done = false;
while (!done)
{
try
{
one.join();
two.join();
three.join();
four.join();
done = true;
}
catch (InterruptedException e)
{
// Handle interrupt determine if need to exit.
}
}
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
How to wait for a number of threads to complete?
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.
wait until all threads finish their work in java
The approach I take is to use an ExecutorService to manage pools of threads.
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
es.execute(new Runnable() { /* your task */ });
es.shutdown();
boolean finished = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.
Java Waiting on multiple Threads, that might create new Threads
You can use a Phaser
to accomplish this. I've wrapped the logic in a new class MyThread
, which you should use in place of Thread
anywhere you require the behaviour you're looking for:
class MyThread extends Thread
{
MyThread(final Runnable runnable, final Phaser phaser)
{
super(() -> {
runnable.run();
phaser.arrive();
});
phaser.register();
}
}
Here is example usage. The main thread creates a thread ("A"), which itself creates a thread ("B"). The main thread waits until all threads are done:
public static void main(String[] args)
{
final Phaser phaser = new Phaser(1);
new MyThread(
() -> {
new MyThread(() -> System.out.println("B"), phaser).start();
System.out.println("A");
try
{
Thread.sleep(1000); // wait for 1s to prove main thread is really waiting
}
catch (InterruptedException e) {}
},
phaser
).start();
phaser.arriveAndAwaitAdvance();
System.out.println("Everything is done");
}
Best practice when waiting for multiple threads - time, count or something else?
This is what a CyclicBarrier is for. It allows you to define spots where threads will wait until all arrive, and then optionally run a Runnable
to perform synchronization or other such thing.
Related Topics
How to Redirect Processbuilder's Output to a String
Extracting Pairs of Words Using String.Split()
Spring 3 MVC: One-To-Many Within a Dynamic Form (Add/Remove on Create/Update)
Capturing Browser Logs with Selenium Webdriver Using Java
Spring Cron Expression for Every Day 1:01:Am
Java's Collections.Shuffle Is Doing What
How to Set Base Url for Rest in Spring Boot
Looking for Java Spell Checker Library
How to Get a Token from a Lucene Tokenstream
Java Server with Multiclient Communication
Can't Rid of 'T' in Localdatetime
In Java, How to Call a Base Class's Method from the Overriding Method in a Derived Class
Implementing Custom Methods of Spring Data Repository and Exposing Them Through Rest
Why Doesn't Java.Lang.Number Implement Comparable