Countdownlatch, a synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.
Main methods
public Countdownlatch (int count);
public void Countdown ();
public void await ()
Example:
Import Java.text.simpledateformat;import Java.util.date;import Java.util.concurrent.countdownlatch;public class Countdownlatchtest {Private final static SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); public static void Main (string[] args) throws interruptedexception {Countdownlatch latch=new countdownlatch (2);//Two worker collaboration Worker worker1=new worker ("Bao", latch); Worker worker2=new worker ("Senan", 4000, latch); Worker1.start (); Worker2.start (); Latch.await ();//wait for all workers to complete the work System.out.println ("All working done at" +sdf.format (new Date ())); }static class Worker extends thread{private String workername;private int worktime;private countdownlatch latch;public Wo Rker (String workername, int worktime, Countdownlatch latch) {this.workername = Workername;this.worktime = WorkTime; This.latch = latch;} public void Run () {System.out.println (Workername + "start at" + Sdf.format (new Date ())); try {thread.sleep (worktime);}catch (Interruptedexception e) {e.printstacktrace ();} Finally{latch.countdown ();//Counter minus one}system.out.println (Workername + "end at" + Sdf.format (new Date ()));}}
The use of Countdownlatch