Countdownlatch is 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.
Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await 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 that has many uses. Countdownlatch, which counts 1 initialized, is used as a simple on/Guan or Portal: All threads calling await are waiting at the entrance until a thread that calls Countdown () opens the portal. N-initialized Countdownlatch can cause a thread to wait until N threads complete an operation, or to wait until an operation completes N.
Simple example
Packagecom.huey.hello.concurrency;ImportJava.util.concurrent.CountDownLatch;/** * * @authorHuey *@version1.0 * @created 2015-2-28*/ Public classWorkerImplementsRunnable {PrivateString Workername; Final PrivateCountdownlatch donesignal; PublicWorker (String workername, Countdownlatch donesignal) { This. Workername =Workername; This. donesignal =donesignal; } @Override Public voidrun () {Try { This. Work (); System.out.println (Workername+ "has completed the job."); Donesignal.countdown (); } Catch(Exception e) {}}Private voidWork ()throwsinterruptedexception {System.out.println (workername+ "is working."); Thread.Sleep (3000); }}
Test
Packagecom.huey.hello.concurrency;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/** * * @authorHuey *@version1.0 * @created 2015-2-28*/ Public classDriver {Static Final intN = 3; Public Static voidMain (string[] args)throwsException {countdownlatch donesignal=NewCountdownlatch (N); Executorservice Pool=Executors.newfixedthreadpool (N); for(inti = 1; I <= N; i++) {String workername= "NO." +i; Pool.execute (NewWorker (Workername, donesignal)); } pool.shutdown (); System.out.println ("Waiting for all workers to complete their jobs."); Donesignal.await (); System.out.println ("All workers have completed their jobs."); System.out.println ("Continue ..."); } }
Test output
The working is. No.2 is working. Waiting for all workers to complete their jobs. No.3 is working. The completed has the job. No.2 has completed the job. No.3 has completed the job. All workers have completed their jobs. Continue ...
Java Concurrency-An analysis of the usage of Countdownlatch