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
.
CountDownLatch
is a universal synchronization tool, it has many uses. Initializes a count of 1 CountDownLatch
as a simple on/Guan, or Portal: countDown()
all called await
threads are waiting at the entrance until the portal is opened by the calling thread. N is initialized CountDownLatch
to allow a thread to wait until the N-Thread completes an operation, or to wait until an operation has finished n the second.
CountDownLatch
A useful feature is that it does not require countDown
the thread that invokes the method to wait until the count arrives 0 o'clock, and before all threads can pass, it simply prevents any thread from continuing through one await
.
ImportJava.util.Random;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Countdown Countdownlatch *@authorDuwenlei **/ Public classCountdownlatchtest { Public Static voidMain (string[] args) {Executorservice service=Executors.newcachedthreadpool (); FinalCountdownlatch Sublatch =NewCountdownlatch (1);//Athlete's FinalCountdownlatch Mainlatch =NewCountdownlatch (3);//Referee's Counter for(inti = 0; I < 3; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Thread" +thread.currentthread (). GetName () + "Ready to stand by"); Sublatch.await (); //The athlete waits for the referee to send a passwordSYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "command already received"); Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "thread completed");//have run outMainlatch.countdown ();//notify the referee}Catch(interruptedexception e) {e.printstacktrace (); } } }; Service.execute (runnable); } Try{Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "outgoing command");//send a password, 3 threads start runningSublatch.countdown ();//counter minus oneSystem.out.println ("Thread" +thread.currentthread (). GetName () + "Waiting for results");//wait for the result after the password is issuedMainlatch.await ();//waiting for all to run outSystem.out.println ("Thread" +thread.currentthread (). GetName () + "All responses received"); } Catch(interruptedexception e) {e.printstacktrace (); } service.shutdown (); } }
Java Thread Synchronization helper class Countdownlatch