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); The constructor method parameter specifies the number of times the count is
public void Countdown(); Countdown method, the current thread calls this method, then the count is reduced by one
public void await() Awaint method, calling this method will block the current thread until the value of the timer is 0
===========================================================================================================
public class Countdownlatchdemo {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 workers collaborating worker Worker1=new worker ("Zhang San", latch); Worker worker2=new worker ("Li Si", 8000, latch); Worker1.start ();//Worker2.start ();//latch.await ();//Waiting for all workers to complete their work System.out.println ("All-work-done at" +sdf.format (new Date ())); } static class Worker extends thread{String workername; int worktime; Countdownlatch latch; Public Worker (String workername, int worktime, Countdownlatch latch) {this.workername=workername; This.worktime=worktime; This.latch=latch; } public void Run() {System.out.println ("Worker" +workername+ "do-work-begin at" +sdf.format (new Date ())); DoWork ();///Worked System.out.println ("Worker" +workername+ "do job complete at" +sdf.format (new Date ())) ; Latch.countdown ();//worker finishes work, counter minus one} private void DoWork () {T ry {thread.sleep (worktime); } catch (Interruptedexception e) {e.printstacktrace (); } } } }
Java multithreaded Collaboration Countdownlatch, the main thread waits for a child thread to end