This is a very practical multi-line program-controlled tool class, the classic scene is the rocket launch, in order to ensure foolproof before the launch of the rocket, often also to carry out various equipment, instrument inspection, only wait for all the inspection completed, the engine can ignite, Countdownlatch constructor accepts an integer as a parameter , which is the count of the current counter.
Public Countdownlatch (int count)
The following is a simple example that demonstrates the use of countdownlatch.
Public classCountdownlatchdemoImplementsRunnable {Static FinalCountdownlatch end =NewCountdownlatch (10); Static FinalCountdownlatchdemo demo =NewCountdownlatchdemo (); /*** When an object implementing interface <code>Runnable</code> was used * To create a thread, start ing the thread causes the object ' s * <code>run</code> method to being called in that separately executing * Thread. * <p> * The general contract of the method <code>run</code> are that it could take any action wha Tsoever. * * @seeThread#run ()*/@Override Public voidrun () {Try{Thread.Sleep (NewRandom (). Nextint (10) * 1000); System.out.println ("Check Complete"); End.countdown ();//finish can be reduced by 1}Catch(interruptedexception e) {e.printstacktrace (); } } Public Static voidMain (string[] args)throwsinterruptedexception {executorservice exec= Executors.newfixedthreadpool (10); for(inti = 0; I < 10; i++) {Exec.submit (demo); } end.await ();//The main thread waits for all 10 threads to complete a task to continue executionSystem.out.println ("fire!"); Exec.shutdown (); }}
The count is 10, which means that 10 threads are required to complete the task, waiting for the thread on Countdownlatch to continue, Countdownlatch.countdown () method, which is the notification Countdownlatch, A thread has completed the task countdown timer can be reduced by 1, using the Countdownlatchawait () method, requiring the main thread to wait for all 10 check tasks to complete. After 10 tasks are complete, the main thread can continue to execute. The main thread waits on the Countdownlatch, and when all the check tasks are complete, the main thread can continue to execute,
Countdown: Countdownlatch (Ready for rocket launch) reading notes