CountDownLatch example of a more general wait/notify mechanism

public void testWaitNotify() throws Exception {
   final Object mutex = new Object();
   Thread t = new Thread() {

public void run() {

// we must acquire the lock before waiting to be notified

synchronized(mutex) {

   System.out.println("Going to wait " +

    "(lock held by " + Thread.currentThread().getName() + ")");

try {

   mutex.wait(); // this will release the lock to be notified (optional timeout can be supplied)

} catch (InterruptedException e) {

   e.printStackTrace();

} 

System.out.println("Done waiting " +

 "(lock held by " + Thread.currentThread().getName() + ")");

   }

}
   };

   t.start(); // start her up and let her wait()

   // not normally how we do things, but good enough for demonstration purposes
   Thread.sleep(1000);

   // we acquire the lock released by wait(), and notify()
   synchronized (mutex) {

System.out.println("Going to notify " +

 "(lock held by " + Thread.currentThread().getName() + ")");

mutex.notify();

System.out.println("Done notify " +

 "(lock held by " + Thread.currentThread().getName() + ")");
   }

}

Output:

Going to wait (lock held by Thread-0) Going to notify (lock held by main) Done notify (lock held by main) Done waiting (lock held by Thread-0)

Related Article:

Reference: Java Concurrency Part 6 – CountDownLatch from our JCG partners at the Carfey Software blog

Share and enjoy!
© 2010-2012 Examples Java Code Geeks. Licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.