Sync Tool Class Java.util.concurrent.CountDownLatch

Source: Internet
Author: User

1, Class introduction
Java.util.concurrent.CountDownLatch

A synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.

Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately. This behavior occurs only once-the count cannot be reset. If you need to reset the count, consider using Cyclicbarrier.

2. Usage Scenarios

In some applications, you need to wait for a certain condition to meet the requirements before you can do the following, and when the thread is finished, the event is triggered for later action. You can use Countdownlatch at this time. Countdownlatch the most important method is countdown () and await (), the former is mainly a countdown, the latter is waiting for the countdown to 0, if not reached 0, only blocking wait.

3. Method Description

Countdown

Countdown ()
Decrements the latch count and, if the count reaches 0, releases all waiting threads. If the current count is greater than 0, the count is reduced. If the new count is zero, all waiting threads are re-enabled for thread scheduling purposes.


If the current count equals zero, no action occurs.

Await

await (Long timeout, timeunit unit)              Throws Interruptedexception
Causes the current thread to wait until the latch is counted down to 0, unless the thread is interrupted or the specified wait time is exceeded. If the current count is zero, this method returns a true value immediately.


If the current count is greater than 0, the current thread is disabled for thread scheduling purposes, and the thread will remain dormant until one of the following three situations occurs:

    • The count reaches 0 due to the call to the countdown () method;
    • One of the other threads interrupts the current thread, or
    • The specified wait time has been exceeded.

If the count reaches 0, the method returns a true value.

If the current thread:

    • The interrupt state of the thread has been set when entering this method;
    • is interrupted while waiting,

Interruptedexception is thrown, and the current thread's interrupted state is cleared. If the specified wait time is exceeded, the return value is false. If the time is less than or equal to zero, this method does not wait at all.

parameter:timeout-the time unit of the Unit-timeout parameter to wait for the longest time.

Returned : returns True if the count reaches 0, or False if the wait time is exceeded before the count reaches 0

Thrown: interruptedexception-if the current thread is interrupted while waiting

4. Usage examples
A Countdouwnlatch instance cannot be reused, that is, it is disposable, the lock cannot be closed once it is opened, and if you want to use it again, consider using Cyclicbarrier. public class Countdownlatchtest {//simulates a 100-metre race and 10 players are ready to wait until the referee commanded.    When everyone gets to the finish line, the game is over.  public static void Main (string[] args) throws Interruptedexception {//Start Countdown lock final Countdownlatch begin =          New Countdownlatch (1);          End of the countdown lock final Countdownlatch end = new Countdownlatch (10);          10 finalists Final Executorservice exec = Executors.newfixedthreadpool (10);              for (int index = 0; index < index++) {final int NO = index + 1; Runnable run = new Runnable () {public void run () {try {//                        If the current count is zero, this method returns immediately.                          Wait for begin.await ();                          Thread.Sleep ((Long) (Math.random () * 10000));                      System.out.println ("No." + No + "arrived");   } catch (Interruptedexception e) {                   } finally {//each player arrives at the end of the line and the end is reduced by one end.countdown ();              }                  }              };        Exec.submit (run);          } System.out.println ("Game Start");          Begin minus one and start playing begin.countdown ();          Wait for end to become 0, i.e. all runners reach the end of End.await ();          System.out.println ("Game over");      Exec.shutdown (); }}




Sync Tool Class Java.util.concurrent.CountDownLatch

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.