Thread Synchronization Tool Countdownlatch

Source: Internet
Author: User

A very typical application scenario for Countdownlatch is that there is one task that wants to go down, but it must wait until the other tasks have been completed before proceeding. If we want to continue down the task of calling an await () method for a Countdownlatch object, the other task executes its own task and calls the countdown () method on the same Countdownlatch object, which calls await () The task of the method will block waiting until the count of the Countdownlatch object is reduced to 0.

There are 3 basic elements of the Countdownlatch class:

    1. The initial value determines the number of events that the Countdownlatch class needs to wait.
    2. Await () method, called by the thread waiting for the end of all events.
    3. The countdown () method, which is called after the event has finished executing.

When you create a Countdownlatch object, the object uses the constructor's parameters to initialize the internal counter. Each time the countdown () method is called, the internal counter of the Countdownlatch object is reduced by one. When the internal counter reaches 0, the Countdownlatch object wakes up all the threads that use the await () method to sleep.

It is not possible to reinitialize or modify the value of the internal counter of the Countdownlatch object . once the value of the counter is initially initialized, the only way to modify it is to use the countdown () method previously used. When the counter reaches 0 o'clock, all calls to the await () method return immediately, and any subsequent calls to the countdown () method will have no effect.

This method differs from the other synchronization methods:

The countdownlatch mechanism is not used to protect shared resources or critical sections. It is used to synchronize one or more threads that perform multiple tasks. It can only be used once. As previously explained, any call to its method is invalid once the Countdownlatch counter reaches 0. If you want to synchronize again, you must create a new object.

The Countdownlatch class has another version of the await () method, which is:

Await (long time, timeunit unit): This method sleeps until it is interrupted, the Countdownlatch internal counter reaches 0, or a specific time passes before the thread wakes up. The Timeunit class contains: Days, HOURS, microseconds, MILLISECONDS, MINUTES, nanoseconds, and SECONDS.

Illustrated by an example of a hundred metre race:

 PackageCn.darrenchan.bigdata.zklock;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classCountdownlatchtest {//The 100-metre race was simulated and 10 players were ready to wait until the referee commanded. When everyone gets to the finish line, the game is over.      Public Static voidMain (string[] args)throwsinterruptedexception {//start of the countdown lock        FinalCountdownlatch begin =NewCountdownlatch (1); //end of the countdown lock        FinalCountdownlatch end =NewCountdownlatch (10); //10 Contestants        FinalExecutorservice exec = Executors.newfixedthreadpool (10);  for(intindex = 0; Index < 10; index++) {            Final intNO = index + 1; Runnable Run=NewRunnable () { Public voidrun () {Try {                          //if the current count is zero, this method returns immediately. //waitbegin.await (); Thread.Sleep ((Long) (Math.random () * 10000)); System.out.println ("No." + No + "arrived"); } Catch(Interruptedexception e) {}finally {                          //when each player reaches the end, end is reduced by oneEnd.countdown ();              }                  }              };        Exec.submit (run); } System.out.println ("Game Start"); //Begin minus one and start playingBegin.countdown (); //wait for end to become 0, that is, all players reach the endend.await (); System.out.println ("Game over");      Exec.shutdown (); }}

Operating effect:

Game Start
No.10 arrived
No.5 arrived
No.9 arrived
No.6 arrived
No.7 arrived
No.3 arrived
No.8 arrived
No.4 arrived
Arrived
No.2 arrived
Game over

Thread Synchronization Tool 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.