Countdownlatch was introduced in java1.5, along with the concurrent tool classes that were introduced together with Cyclicbarrier, Semaphore, Concurrenthashmap, and Blockingqueue, They all exist under the Java.util.concurrent package. Countdownlatch This class enables a thread to wait for other threads to complete their work before executing. For example, the main thread of the application wants to execute after all the framework services have been started by the threads that are responsible for starting the framework service. The Countdownlatch is implemented by a counter, where the initial value of the counter is the number of threads. Each time a thread finishes its task, the value of the counter is reduced by 1. When the counter value reaches 0 o'clock, it means that all the threads have completed the task, and then the thread waiting on the latch can resume the execution of the task.
For example: If we have 10 Excel documents, each of which has a bank record for one year, we want to summarize all of the data in these documents, and find out your records of all water can consider using Countdownlatch
The pseudo code is as follows:
public class work implements Runnable {private countdownlatch latch; Private String msg; private int sum=0 ; Public work (String msg, countdownlatch latch) {this.msg= msg; this.latch= latch;} public Void run () {while (true ) {System.out . Print (msg); Latch.countdown ();//Counter minus 1 break ;}}
Import java.util.concurrent.countdownlatch;/** * by LV xiao Long * */public class App {public static void Main (string[] args) { //The value of the set counter here is 2, and the countdown operation will change to 0 if it executes two times in the child thread. will return to the main thread countdownlatch countdownlatch=new countdownlatch (2); Working work=new Work ("Thread 1 complete \ n", countdownlatch); Thread thread=new thread (work); Thread.Start () work=new working ("Thread 2 job complete \ n", Countdownlatch); Thread=new Thread (work); Thread.Start (); Try {countdownlatch.await(); System.out.println ("All work is done! \ n " ); } catch (Interruptedexception e) {e.printstacktrace (); }}}
Introduction to Java Countdownlatch usage