Introduced
Countdownlatch is a synchronous helper class that allows one or more threads to wait until the other threads have finished executing before starting execution.
Initializes the countdownlatch with the given count , which means the number of threads to be waited for execution.
Countdown (), count minus 1 per call
The main program execution to the await () function blocks the execution of the waiting thread until the count is 0
Implementation principle
The counter is implemented by using a lock (shared lock, exclusive lock)
Example 1
Scene: Simulate 10 people running. After 10 people ran out, they shouted "Game over."
PackageCom.jihite;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classCountdownlatchtest {Private Static Final intRunner_count = 10; Public Static voidMain (string[] args)throwsinterruptedexception {FinalCountdownlatch begin =NewCountdownlatch (1); FinalCountdownlatch end =NewCountdownlatch (Runner_count); FinalExecutorservice exec = Executors.newfixedthreadpool (10); for(inti = 0; i < Runner_count; i++) { Final intNO = i + 1; Runnable Run=NewRunnable () {@Override Public voidrun () {Try{begin.await (); Thread.Sleep ((Long) (Math.random () * 10000)); System.out.println ("No." + No + "arrived"); } Catch(interruptedexception e) {e.printstacktrace (); } finally{end.countdown (); } } }; Exec.submit (run); } System.out.println ("Game Start ..."); Begin.countdown (); End.await ();//end.await (timeunit.seconds);System.out.println ("Game over."); Exec.shutdown (); }}
Analysis: 2 counters are defined in the code, and the number is 1 and 10, respectively.
If Begin.countdown () is not executed, the process is consistently blocked at begin.await ()
The main process executes to End.awit () Blocking wait for end counter clear 0, each time the process executes countdown () minus 1, all execution of the primary process continues down
Output
Game Start ... No. 6 Arrivedno. 4 Arrivedno. Ten Arrivedno. 3 Arrivedno. 9 Arrivedno. 5 Arrivedno. 8 Arrivedno. 7 Arrivedno. 1 arrivedno. 2 arrivedgame over.
Example 2 (similar to join)
Scenario: There are 3 Worker:worker1, Worker2, and Worker3 on the pipeline, which can only be performed when Worker1 and Worker2 are completed Worker3
Workercount.java
PackageCom.jihite;ImportJava.util.concurrent.CountDownLatch; Public classWorkercountextendsThread {PrivateString name; Private LongTime ; PrivateCountdownlatch Countdownlatch; PublicWorkercount (String name,LongTime , Countdownlatch Countdownlatch) { This. Name =name; This. Time =Time ; This. Countdownlatch =Countdownlatch; } @Override Public voidrun () {Try{System.out.println (name+ "Start work"); Thread.Sleep (time); SYSTEM.OUT.PRINTLN (Name+ "work done, time consuming:" +Time ); Countdownlatch.countdown (); System.out.println ("Countdownlatch.getcount ():" +Countdownlatch.getcount ()); } Catch(interruptedexception e) {e.printstacktrace (); } }}
Countdownlatch implementation:
@Test Public voidCountdownlatchtest ()throwsinterruptedexception {intCOUNT = 2; FinalCountdownlatch Countdownlatch =NewCountdownlatch (COUNT); Workercount Worker0=NewWorkercount ("lilei-0", (Long) (Math.random () * 10000), Countdownlatch); Workercount Worker1=NewWorkercount ("Lilei-1", (Long) (Math.random () * 10000), Countdownlatch); Worker0.start (); Worker1.start (); Countdownlatch.await (); System.out.println ("Ready for Work"); Workercount Worker2=NewWorkercount ("Lilei-2", (Long) (Math.random () * 10000), Countdownlatch); Worker2.start (); Thread.Sleep (10000); }
Output:
lilei-0 Start work Lilei-1 start work Lilei-1 work done, time: 4039countdownlatch.getcount ():1lilei- 0 work completed, time consuming: 9933countdownlatch.getcount ():0 ready to work Lilei-2 start work Lilei-2 work completed, time consuming: 6402 Countdownlatch.getcount ():0
The scene join can also be done
Worker.java
PackageCom.jihite; Public classWorkerextendsthread{PrivateString name; Private LongTime ; PublicWorker (String name,LongTime ) { This. Name =name; This. Time =Time ; } @Override Public voidrun () {Try{System.out.println (name+ "Start work"); Thread.Sleep (time); SYSTEM.OUT.PRINTLN (Name+ "work done, time consuming:" +Time ); } Catch(interruptedexception e) {e.printstacktrace (); } }}
Join implementation
@Test Public voidJointest ()throwsinterruptedexception {Worker Worker0=NewWorker ("lilei-0", (Long) (Math.random () * 10000)); Worker Worker1=NewWorker ("Lilei-1", (Long) (Math.random () * 10000)); Worker Worker2=NewWorker ("Lilei-2", (Long) (Math.random () * 10000)); Worker0.start (); Worker1.start (); Worker0.join (); Worker1.join (); System.out.println ("Ready for Work"); Worker2.start (); Thread.Sleep (10000); }
Output
lilei-0 Start work Lilei-1 start work Lilei-1 work completed, time consuming: 4483lilei-0 work completed, time-consuming: 6301 ready to work Lilei- 2 start work Lilei-2 work completed, time consuming: 6126
In that case, what is the difference between Countdownlatch and join? By the following scenario three can be seen
Instance 3 (different from join)
Scene: The pipeline has 3 worker:worker1, Worker2, Worker3, only when the stage of Worker1 and Worker2 are executed before they can be executed Worker3
Workercount2.java
PackageCom.jihite;ImportJava.util.concurrent.CountDownLatch; Public classWorkerCount2extendsThread {PrivateString name; Private LongTime ; PrivateCountdownlatch Countdownlatch; PublicWorkerCount2 (String name,LongTime , Countdownlatch Countdownlatch) { This. Name =name; This. Time =Time ; This. Countdownlatch =Countdownlatch; } @Override Public voidrun () {Try{System.out.println (name+ "Start Phase 1 Work"); Thread.Sleep (time); SYSTEM.OUT.PRINTLN (Name+ "Phase 1 complete, time consuming:" +Time ); Countdownlatch.countdown (); SYSTEM.OUT.PRINTLN (Name+ "Start Phase 2 Work"); Thread.Sleep (time); SYSTEM.OUT.PRINTLN (Name+ "Phase 2 complete, time consuming:" +Time ); } Catch(interruptedexception e) {e.printstacktrace (); } }}
This is not possible with join, only with Countdownlatch
@Test Public voidCountDownLatchTest2 ()throwsinterruptedexception {intCOUNT = 2; FinalCountdownlatch Countdownlatch =NewCountdownlatch (COUNT); WorkerCount2 Worker0=NewWorkerCount2 ("lilei-0", (Long) (Math.random () * 10000), Countdownlatch); WorkerCount2 Worker1=NewWorkerCount2 ("Lilei-1", (Long) (Math.random () * 10000), Countdownlatch); Worker0.start (); Worker1.start (); Countdownlatch.await (); System.out.println ("Ready for Work"); WorkerCount2 Worker2=NewWorkerCount2 ("Lilei-2", (Long) (Math.random () * 10000), Countdownlatch); Worker2.start (); Thread.Sleep (10000); }
Output
lilei-0 Start Phase 1 work Lilei-1 start Stage 1 work Lilei-0 Stage 1 complete, time consuming: 3938lilei-0 start Phase 2 work Lilei-1 Stage 1 complete , time-consuming: 6259lilei-1 start Phase 2 work Readiness Lilei-2 start Phase 1 work Lilei-0 Stage 2 complete, time-consuming: 3938lilei- 1 Phase 2 complete, time-consuming: 6259lilei-2 Phase 1 complete, time-consuming: 7775lilei-2 start Phase 2 work
Java Multithreading to Countdownlatch use instances