The Java.util.concurrent.CountDownLatch class is a synchronous counter that is constructed with an int parameter, which is the initial value of the counter, each time the countdown () method is called, the counter is reduced by 1, the counter is greater than 0 o'clock, and the await () Method will block the program from continuing execution.
1. The constructor method parameter specifies the number of times the count
2.countDown method, the current thread calls this method, then the count is reduced by one
3.awaint method, calling this method will block the current thread until the value of the timer is 0
Package Cn.baokx;import Java.util.random;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.timeunit;class Subthread implements Runnable{private Countdownlatch downlatch;private String Name;public subthread (countdownlatch downlatch,string name) {This.downlatch = Downlatch;this.name = name;} @Overridepublic void Run () {System.out.println (this.name+ "is working ..."); try {TimeUnit.SECONDS.sleep (New Random (). Nextint (10)); System.out.println (THIS.name + "have finished its working ..."); catch (Interruptedexception e) {e.printstacktrace ();} Finally{this.downlatch.countdown ();}}} public class Countdownlatchtest {public static void main (string[] args) {Countdownlatch downlatch = new Countdownlatch (4); Subthread st1 = new Subthread (Downlatch, "subThread1"); Subthread st2 = new Subthread (Downlatch, "subThread2"); Subthread st3 = new Subthread (Downlatch, "subThread3"); Subthread st4 = new Subthread (Downlatch, "subThread4"); System.out.println ("Mainthread is wating ..."); new Thread (ST1). Start(); new Thread (ST2). Start (); new Thread (ST3). Start (); new Thread (ST4). Start (); try {downlatch.await ();} catch ( Interruptedexception e) {e.printstacktrace ();} System.out.println ("All subthread have finished,mainthread can begin to checking ...");}}
Basic usage of Java.util.concurrent.CountDownLatch class