Sometimes there is a need for multiple threads to work at the same time, and then several of them can be executed concurrently, but one thread needs to wait until the other threads have finished working before starting. For example, open multiple threads to download a large file, each thread only download a fixed section, and finally by another thread splicing all the fragments, then we can consider using Countdownlatch to control concurrency.
Countdownlatch is an auxiliary class provided by Java under the Java.util.concurrent package, which can be viewed as a counter, which maintains a count count internally, except that the operation of this counter is atomic, and only one thread can operate the counter, Coun Tdownlatch an initial count value is passed through the constructor, the caller can reduce the count by 1 by calling the Coundownlatch object's Cutdown () method, and if the await () method on the object is called, the caller will always be blocked here. Until someone else passes the Cutdown method, the count is reduced to 0 before the execution can continue.
ImportJava.util.concurrent.CountDownLatch; Public classSample {/*** counter, used to control thread * Incoming parameter 2, indicating counter count of 2*/ Private Final StaticCountdownlatch Mcountdownlatch =NewCountdownlatch (2); /*** Example worker thread class*/ Private Static classWorkingthreadextendsThread {Private FinalString Mthreadname; Private Final intMsleeptime; PublicWorkingthread (String name,intsleeptime) {Mthreadname=name; Msleeptime=Sleeptime; } @Override Public voidrun () {System.out.println ("[" + Mthreadname + "] started!"); Try{thread.sleep (msleeptime); } Catch(interruptedexception e) {e.printstacktrace (); } mcountdownlatch.countdown (); System.out.println ("[" + Mthreadname + "] end!"); } } /*** Sample Thread class*/ Private Static classSamplethreadextendsThread {@Override Public voidrun () {System.out.println ("[Samplethread] started!"); Try { //will block here waiting for the count in Mcountdownlatch to become 0;//that is, wait for another Workingthread call Countdown ()mcountdownlatch.await (); } Catch(Interruptedexception e) {} System.out.println ("[Samplethread] end!"); } } Public Static voidMain (string[] args)throwsException {//First Run Samplethread NewSamplethread (). Start (); //Run two worker threads//worker thread 1 runs for 5 seconds NewWorkingthread ("WorkingThread1", 5000). Start (); //worker thread 2 runs for 2 seconds NewWorkingthread ("WorkingThread2", 2000). Start (); }}
Operation Result:
[Samplethread] started!
[WorkingThread1] started!
[WorkingThread2] started!
[WorkingThread2] end!
[WorkingThread1] end!
[Samplethread] end!
achieved its purpose. Of course there are other ways to do this, and this article simply introduces a way to use Countdownlatch.
Controlling multiple thread execution sequences using Countdownlatch