package aaa.bbb;import java.text.simpledateformat;import java.util.date;import Java.util.concurrent.countdownlatch;public class t1 {final static simpledateformat sdf = new simpledateformat ("Yyyy-mm-dd hh:mm:ss");p ublic static void Main (String[] args) throws exception {countdownlatch countdownlatch = new countdownlatch (3); Worker w1 = new worker ("W1", 2000, countdownlatch); Worker w2 = new worker ("W2", 5000, countdownlatch); W1.start ();//w2.start ();// Countdownlatch.await ();// waits for all workers to complete the 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;} @Overridepublic void run () {system.out.println ("worker " + workername + " do work begin at " + sdf.format (New date ())); Try {thread.sleep ( Worktime);} catch (interruptedexception e) {e.printstacktrace ();} System.out.println ("worker " + workerName + " do work complete at "+ sdf.format (New date ())); Latch.countdown ();// Worker completes work, counter minus one}}}
Java Countdownlatch Thread Helper classes