Countdownlatchextends Object
A synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.
Initialized with the given count CountDownLatch
. Because the method is called countDown()
, the await
method will remain blocked until the current count reaches 0. After that, all the waiting threads are freed, and await
all subsequent calls are returned immediately. This behavior occurs only once-the count cannot be reset. If you need to reset the count, consider using CyclicBarrier
.
Case code:
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
/**
* Thread Timer
*
* @author Wangyi
* @verion 1.0 <br/>
* <a href= "www.baidu.com" > Baidu </a>
*/
public class Countdownlatchtest {
public static void Main (string[] args) {
Executorservice ThreadPool = Executors.newcachedthreadpool ();
Final Countdownlatch cdh1 = new Countdownlatch (1);
Final Countdownlatch CDH2 = new Countdownlatch (3);
for (int i = 1; I <= 3; i++) {
Runnable Runnable = new Runnable () {
@Override
public void Run () {
try {
System.out.println (Thread.CurrentThread (). GetName ()
+ "Waiting for Command:");
Cdh1.await ();
Thread.Sleep ((int) (Math.random () * 10000));
System.out.println (Thread.CurrentThread (). GetName ()
+ "results in process ...");
Thread.Sleep ((int) (Math.random () * 10000));
System.out.println (Thread.CurrentThread (). GetName ()
+ "task completed");
Cdh2.countdown ();
} catch (Exception e) {
E.printstacktrace ();
}
}
};
Threadpool.execute (runnable);
}
try {
Thread.Sleep ((int) (Math.random () * 10000));
System.out.println (Thread.CurrentThread (). GetName ()
+ "Start publishing tasks, waiting to receive results ...");
Cdh1.countdown ();
Cdh2.await ();
System.out.println (Thread.CurrentThread (). GetName () + "results obtained");
} catch (Exception e) {
E.printstacktrace ();
}
Threadpool.shutdown ();
}
}
Multi-threaded Sync tool (Countdownlatch)