Countdownlatch, a synchronization helper class that allows one or more threads to wait until a group of operations are being performed in another thread.
Main Method
Public countdownlatch (INT count );
Public voidCountDown();
Public voidAwait() Throws
Interruptedexception
The constructor parameter specifies the count.
Countdown method. If the current thread calls this method, the count is reduced by one.
Awaint method. Calling this method will block the current thread until the timer value is 0.
Test example:
Package test. thread;
Import java. Text. simpledateformat;
Import java. util. date;
Import java. util. Concurrent. countdownlatch;
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); // collaboration between two workers
Worker worker1 = new Worker ("zhangsan", 5000, latch );
Worker worker2 = new Worker ("li si", 8000, latch );
Worker1.start ();//
Worker2.start ();//
Latch. await (); // wait for all workers to finish 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 (); // working
System. out. println ("Worker" + workerName + "do work complete at" + sdf. format (new Date ()));
Latch. countDown (); // The worker completes the work and the counter is reduced by one.
}
Private void doWork (){
Try {
Thread. sleep (workTime );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
Output:
Worker zhang san do work begin at 10:04:58
Worker li si do work begin at 10:04:58
Worker zhang san do work complete at 10:05:03
Worker li si do work complete at 10:05:06
All work done at 10:05:06
Http://www.iteye.com/topic/581476