I want my main thread to wait until one out of many threads signals\complete.
I don't need to wait for all of them to signal\finish, just one.
What will be the best practice of accomplishing such requirement?
I want my main thread to wait until one out of many threads signals\complete.
I don't need to wait for all of them to signal\finish, just one.
What will be the best practice of accomplishing such requirement?
CountDownLatch
will do what you want. Initialize it to 1 and wait. The first thread to countDown()
on it will allow the waiting thread to proceed.
public class CountDownLatchTest
{
public static void main(String[] args) throws InterruptedException {
CountDownLatch gate = new CountDownLatch( 1 );
for( int i = 0; i < 3; i++ ) {
new Thread( new RandomWait( gate, i ) ).start();
}
gate.await();
System.out.println("Done");
}
private static class RandomWait implements Runnable
{
CountDownLatch gate;
int num;
public RandomWait( CountDownLatch gate, int num )
{
this.gate = gate;
this.num = num;
}
public void run() {
try {
Thread.sleep( (int)(Math.random() * 1000) );
System.out.println("Thread ready: "+num);
gate.countDown();
} catch( InterruptedException ex ) {
}
}
}
}
You do something like this
boolean complete=false;
Object waitSync = new Object();
// the waiter has something like this
void waitFor() {
synchronized (waitSync) {
try {
while (!complete)
waitSync.wait();
} catch (Exception e) {}
}
}
// each worker calls something like this when completed
synchronized (waitSync) {
complete = true;
waitSync.notifyAll();
}
The simpler Condition interface would do. As an added bonus you get to choose your lock using Lock.newCondition()
A CountdownLatch can only be released once, so that may or may not be what you want.
See also : Put one thread to sleep until a condition is resolved in another thread