A detailed explanation and example of Java.util.concurrent.CountDownLatch

Source: Internet
Author: User
Java.util.concurrent.CountDownLatch class details and examplesOriginal August 13, 2013 19:58:19 2940 1 2

As can be seen from the name, Countdownlatch is a reciprocal count of the lock,
When the countdown to 0 o'clock triggers the event, which is the unlock, the other person can enter.
In some applications, it is necessary to wait for a certain condition to be required to do the following, and when the thread completes, it triggers the event for subsequent operations.


The most important method of Countdownlatch is Countdown () and await (), the former is mainly the penultimate, the latter is waiting for the countdown to 0, if not reached 0, only blocking wait.

The Countdownlatch class is a synchronous counter that passes in the int parameter, which is the initial value of the counter, Countdown () method, each time the counter is reduced by 1, the counter is greater than 0 o'clock, and the await () method blocks the program from continuing execution. Countdownlatch can be seen as an inverted-count latch that triggers a specific event when the count is reduced to 0 o'clock. With this feature, you can let the main thread wait for the end of the child thread. The following is illustrated by an example of a mock athlete contest.

A very typical scenario for Countdownlatch is that you have a task that you want to perform down, but you have to wait until the other task has finished executing before you can proceed down. If the task we want to continue to execute calls a Countdownlatch object's await () method, and the other task finishes its own task, invokes the countdown () method on the same Countdownlatch object, which await () The task of the method blocks the wait until the count of the Countdownlatch object is reduced to 0.

The following example simply illustrates the use of countdownlatch, simulating the 100-metre race, where 10 contestants are ready to wait until the referee command. When everyone is at the end, the game is over.


Package com.eyesmore.concurrent;   
Import Java.util.concurrent.CountDownLatch;   
Import Java.util.concurrent.ExecutorService;   
  
Import java.util.concurrent.Executors;   
       
    public class Countdownlatchdemo {private static final int play_amount = 10;  
         public static void Main (string[] args) {* * competition begins: As soon as the referee says it starts, all runners can start running.   
           
        Countdownlatch begin = New Countdownlatch (1); * * * When each member runs to the end, report a arrival and all personnel arrive, the game ends * */countdownlatch end = new Countdownlatch (Play_amo   
         UNT);   
        Player[] plays = new Player[play_amount];   
         for (int i = 0;i<play_amount;i++) {Plays[i] = new Player (i+1,begin,end);   
        } executorservice exe = Executors.newfixedthreadpool (play_amount);   
         for (Player p:plays) {//positions Exe.execute (p);   
         } System.out.println ("Start of Game"); Begin.counTdown ()//announce start try {end.await ();/wait for End} catch (Interruptedexception e) {   
         E.printstacktrace ();   
         finally {System.out.println ("Game Over");   
     //Note: At this point the main thread is already finished, but EXE thread is not closed if it is not exe.shutdown ();   
       
    } class Player implements Runnable {private int id;   
       
    Private Countdownlatch begin;   
  
    Private Countdownlatch end;   
        public Player (int ID, countdownlatch begin, Countdownlatch end) {super ();   
        This.id = ID;   
        This.begin = begin;   
     This.end = end; public void Run () {try {begin.await ()}//must wait until the referee countdown to 0 to start T   
               
         Hread.sleep ((Long) (Math.random () *100))//simulate the time needed for running System.out.println ("Play" +id+ "has arrived.");   
          catch (Interruptedexception e) {   E.printstacktrace ();   finally {End.countdown ()//To the judges report to the finish line}}


Copyright NOTICE: This article is the original article of the blogger, without the permission of the blogger may not be reproduced. Report Tags: multithreading/Java/Currently you are not logged in, please login or register after comment w395115323 2017-04-24 18:461 floor good. Reply to more comments

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.