Countdownlath, which can be understood as a countdown timer, is a helper class for thread synchronization. It initializes the initial value of the countdown timer (New countdownlath (100) with the specified value )),
The countdown method of the called object will reduce the timer by 1. When it is reduced to 0, this object will wake up the thread waiting to call the await method of the object. If the counter is already 0,
When the following thread calls the await method, it will return immediately without blocking.
A running counter is simulated below:
Import java. util. Random;
Import java. util. Concurrent. countdownlatch;
/**
*
* @ Author yangbaobao
*
*/
Public class countdownlathdemo {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Final countdownlatch order = new countdownlatch (1 );
Final countdownlatch waitdown = new countdownlatch (100 );
Final countdownlatch countdown = new countdownlatch (100 );
For (INT I = 0; I <100; I ++ ){
New thread (New runnable (){
Public void run (){
Try {
Thread. Sleep (new random (). nextint (1000 ));
System. Out. println (thread. currentthread (). getname () + "-- preparing ");
Waitdown. Countdown ();
Order. Await ();
System. Out. println (thread. currentthread (). getname () + "-- run ");
Thread. Sleep (new random (). nextint (2000 ));
System. Out. println (thread. currentthread (). getname () + "-- reach the end ");
Countdown. Countdown ();
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}). Start ();
}
Try {
Waitdown. Await ();
System. Out. println ("Everyone has arrived ");
System. Out. println ("shot ");
Order. Countdown ();
Countdown. Await ();
System. Out. println ("Everyone has reached the end ");
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}