0

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?

danieln
  • 4,795
  • 10
  • 42
  • 64
  • put on some code also on how you are creating the threads like are all the threads created by one executor or many executors create threads.. give just the skeleton of thread creation – awsome Dec 24 '15 at 18:32
  • Use a [lock](https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html) – Vince Dec 24 '15 at 18:34

3 Answers3

4

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 ) {
         }
      }
   }
}
markspace
  • 10,621
  • 3
  • 25
  • 39
0

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();
        }
gpasch
  • 2,672
  • 3
  • 10
  • 12
0

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

Community
  • 1
  • 1
kervin
  • 11,672
  • 5
  • 42
  • 59