Countdownlatch a synchronous helper class that allows one or more threads to wait until a set of operations that are executing in another thread is completed.
Latching can delay the progress of a thread until it reaches the terminating state, and latching can be used to ensure that certain activities continue until other activities are completed:
- Ensure that a calculation does not continue until all the resources it needs are initialized;
- Ensure that a service is started after all other services it relies on have been started;
- Wait until all participants in an operation are ready before proceeding.
PackageCom.company;ImportJava.util.concurrent.CountDownLatch;/** Countdownlatch: Latching, in the completion of certain operations, only the operation of all other threads is complete, the current operation continues to execute*/ Public classTestcountdownlatch { Public Static voidMain (string[] args) {FinalCountdownlatch latch =NewCountdownlatch (50); Latchdemo LD=NewLatchdemo (latch); LongStart =System.currenttimemillis (); for(inti = 0; I < 50; i++) { NewThread (LD). Start (); } Try{latch.await (); } Catch(Interruptedexception e) {}LongEnd =System.currenttimemillis (); System.out.println ("Time-consuming:" + (End-start)); }}classLatchdemoImplementsRunnable {PrivateCountdownlatch latch; PublicLatchdemo (Countdownlatch latch) { This. Latch =latch; } @Override Public voidrun () {Try { for(inti = 0; I < 50000; i++) { if(i% 2 = = 0) {System.out.println (i); } } } finally{latch.countdown (); } }}
Results:
A bit longer to intercept the second half of the paragraph bar:
499944999649998 Time-consuming:7301
Java Multithreading--Countdownlatch latching