A synchronization helper class that agrees that one or more threads are waiting until a set of operations that are running in another thread is completed.
Initializes the countdownlatch with the given count. Because the countdown () method is called, before the current count reaches 0. The await method will always be blocked. After. All the waiting threads are freed, and all the calls to await will be returned immediately. Such a phenomenon only occurs once-the count cannot be reset. Suppose you need to reset the count. Please consider using Cyclicbarrier.
Countdownlatch is a universal synchronization tool. It has very many uses.
The Countdownlatch initialized with Count 1 is used as a simple on/Guan device. Or Portal: Before opening the portal by calling the thread of Countdown (). All threads that call await are waiting at the entrance.
An n-initialized Countdownlatch enables a thread to wait until the N-thread finishes an operation, or to wait until an operation has finished n the second.
A practical feature of Countdownlatch is that it does not require a thread that calls the countdown method to wait until the count arrives 0 o'clock. Before all threads can pass, it simply prevents any thread from continuing through an await.
The following is a simple example
Demonstrates starting 5 threads. Wait until all threads have finished running to print the final result
Package Com.lala.shop;import Java.time.duration;import Java.time.instant;import java.util.random;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.timeunit;public class CountDownLatchDemo {/** * Start a size thread, wait until all threads have finished running, print the final result * @param size */public void demo (final int size) {Countdownlatch CDL = new Countdownlatch (si Ze); Instant start = Instant.now (); for (int i=1;i<=size;i++) {new Thread (()} {try{long time = new Long (new Random (). N Extint (10)); TimeUnit.SECONDS.sleep (time); System.out.println (Thread.CurrentThread (). GetName () + "sleep" + Time + "then finish ..."); Cdl.countdown (); catch (Interruptedexception e) {e.printstacktrace ();}}). Start ();} try {cdl.await ();} catch (Interruptedexception e) {e.printstacktrace ();} Instant end = Instant.now ();D uration time = Duration.between (start, end); Long seconds = time.getseconds ();//seconds = System.ou T.println ("Finish this task ... spend time" + seconds + "seconds");} public static void Main (string[] args) {New Countdownlatchdemo (). Demo (5);}}
The Countdownlatch of Java concurrent programming