Countdownlath countdown timer

Source: Internet
Author: User

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 ();
}
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.