Synchronous Helper Class Countdownlatch usage

Source: Internet
Author: User
Tags finally block

Countdownlatch is a synchronous helper class, like a countdown counter, when an object is created, the initial value is set by the constructor method, and the await () method that invokes the Countdownlatch object causes the current thread to be in a wait state, calling Countdown () method, the counter is reduced by 1, and when the count reaches 0 o'clock, all waiting threads start executing. The common methods it provides:

 Public Countdownlatch (int  count);     Public void countdown ();             Public void throws interruptedexception;   Calling this method will block the current thread until the value of the timer is 0

Use the following methods:

 PackageBasic;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classTestcountdown {Private Static Final intPlayer_amount = 5;  Public Static voidMain (string[] args) {/*for each athlete, Countdownlatch starts the race after minus 1.*/Countdownlatch begin=NewCountdownlatch (1); /*for the whole game, all the athletes are finished.*/Countdownlatch End=NewCountdownlatch (Player_amount); Player[] Players=NewPlayer[player_amount];  for(inti = 0; i < Player_amount; i++) {Players[i]=NewPlayer (i + 1, begin, end); }        /*set a specific thread pool with a size of 5*/Executorservice Executorservice=Executors.newfixedthreadpool (Player_amount);  for(Player player:players) {/*Assigning Threads*/Executorservice.execute (player); } System.out.println ("Race begins!"); /*All players wait for the start of the game signal*/Begin.countdown (); Try {            /*wait until the end state becomes 0, which is the end of the game*/end.await (); } Catch(interruptedexception e) {e.printstacktrace (); } finally{System.out.println ("Race ends!");    } executorservice.shutdown (); }}classPlayerImplementsRunnable {Private Final intID; Private FinalCountdownlatch begin; Private FinalCountdownlatch end;  PublicPlayer (intID, Countdownlatch begin, Countdownlatch end) {        Super();  This. ID =ID;  This. Begin =begin;  This. end =end; } @Override Public voidrun () {Try {            /*wait for begin to have a status of 0*/begin.await (); /*randomly allocated time, that is, athlete completion time*/Thread.Sleep ((Long) (Math.random () * 100)); System.out.println ("Play" + ID + "arrived."); } Catch(interruptedexception e) {e.printstacktrace (); } finally {            /*The end state minus 1, the current thread of the athlete finishes the match*/End.countdown (); }    }}

In the Code, Begin.countdown () is the start of the race signal, five begin.await () threads start executing, and then execute End.countdown () in the finally block after execution, and when the counter is reduced to 0, Wake up End.await () in the main method, and the program goes down and prints the game over.

causes the current thread to wait until the latch have counted down to zero, unless the th Read is interrupted. If the current count was zero then this fo R Thread scheduling purposes and lies dormant until one of them things happen:1.the Count reaches zero due to invocations of the countdown () method; or 2.Some other thread interrupts the current thread.

if the current Thread:has it interrupted status set on entry to this method; or is interrupted while waiting, then java.lang.InterruptedException are thrown and the current thread ' s interrupted status is cleared. throws:java.lang.interruptedexception if the current thread is interrupted while waiting public void await () Interruptedexception { sync.acquiresharedinterruptibly (1}

Above is the core method await () the JDK source code!

Synchronous Helper Class Countdownlatch usage

Related Article

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.