Threading Tool Class-Countdownlatch

Source: Internet
Author: User

Countdownlatch Official User's manual: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

First, the principle

Countdownlatch is a very practical multi-line program-controlled tool class. Count down in English to the countdown, latch meaning for the latch, you can simply countdownlatch called the countdown timer. The latch means: Lock the door, not let the inside of the thread run out. As a result, this tool is typically used to control thread waits, which allows a thread to wait until the countdown is over and start executing.

The Countdownlatch internally maintains a count count, except that the operation of this counter is atomic, while only one thread can operate the counter. Countdownlatch an initial count value is passed through the constructor, the caller can reduce the count by 1 by calling the Coundownlatch object's Countdown () method, and if the await () method on the object is called, the caller will always be blocked here. Until someone else passes the countdown method, the count is reduced to 0 before the execution can continue.

A typical application scenario for Countdownlatch is rocket launch. Before the launch of the rocket, in order to ensure foolproof, often to carry out various equipment, instrument inspection. The engine can only fire after all the checks have been completed. This scenario is ideal for using Countdownlatch. It allows the ignition thread to wait for all check threads to complete before executing.

Second, the API

Main methods

    • public Countdownlatch (int count);

The constructor method parameter specifies the number of times the count

    • public void Countdown ();

This method is called by the current thread, and the count is reduced by one

    • public void await () throws Interruptedexception

Calling this method will block the current thread until the value of the timer is 0

Third, Demo

A typical use of Countdownlatch is:

A group of workers threads use two countdown latches (a set of worker threads uses two countdownlatch).

Sample Usage: A group of worker threads use two countdown latches (a set of worker threads uses two Countdownlatch):

    • The first is a start signal this prevents any worker from proceeding until the driver are ready for them to proceed;
    • The second is a completion signal this allows the driver to wait until all workers has completed

Here is a demo to illustrate the use of countdownlatch.

Program features: Simulate multi-threaded download, merge threads wait until all download tasks are complete and start merging.

/*** Typical usage of Countdownlatch 2 * code feature: Use multiple download threads to implement the download until all tasks are complete and merge threads begin merging. *  * @authorLP **/ Public classCountDownLatchDemo2 { Public Static voidMain (string[] args)throwsinterruptedexception {intN = 8; Countdownlatch startsignal=NewCountdownlatch (1);//startsignal Control beginsCountdownlatch donesignal =NewCountdownlatch (N);//Executorservice Executor= Executors.newfixedthreadpool (N + 1);//8 Download threads, 1 merge Threads//Let all threads proceedStartsignal.countdown (); //n Download task start execution         for(inti = 0; i < N; ++i) {Executor.execute (Newdownloadrunnable (startsignal,donesignal, i)); }        //wait for all to finishDonesignal.await ();//block until the counter is 0//Perform merge TasksExecutor.execute (Newmergerunnable ());    Executor.shutdown (); }}/*** Download Thread*/classDownloadrunnableImplementsRunnable {Private FinalCountdownlatch startsignal; Private FinalCountdownlatch donesignal; Private Final inti;  PublicDownloadrunnable (Countdownlatch startsignal, Countdownlatch donesignal,inti) { This. startsignal =startsignal;  This. donesignal =donesignal;  This. i =i; }     Public voidrun () {Try{startsignal.await ();//Current thread Waitsdodownload (i);        Donesignal.countdown (); } Catch(interruptedexception e) {e.printstacktrace (); }    }    Private voidDodownload (inti) {System.out.println ("Thead:" + i + "Download Complete"); }}

Another typical usage would is to divide a problem into N parts, describe each part with a Runnable this executes that por tion and counts down in the latch, and queue all the runnables to an Executor. When all sub-parts is complete, the coordinating thread is able to pass through await. (When the threads must repeatedly count down in the this-is, instead use a CyclicBarrier .)

Another typical use is to break up a problem into n parts, use runnable to describe each part of the task, each runnable after the execution of the latch number minus 1, and all runnable are added to the executor. When all child part tasks are completed, the orchestration thread is able to start execution after an await. (Use Cyclicbarrier instead when the thread must have a repeatable countdown)

/*** Typical usage of countdownlatch 1 * Code features: Simulate multi-threaded download-Download using multiple download threads, wait until all tasks are complete and merge threads begin merging. *  * @authorLP **/ Public classCountdownlatchdemo { Public Static voidMain (string[] args)throwsinterruptedexception {intN = 8; Countdownlatch donesignal=NewCountdownlatch (N);//counter starts from N CountdownExecutorservice executor = Executors.newfixedthreadpool (N + 1);//n Download threads, 1 merge Threads//n Download task start execution         for(inti = 0; i < N; ++i) {Executor.execute (Newdownloadrunnable (donesignal, i)); }        //wait for all to finishDonesignal.await ();//block until the counter is 0//Perform merge TasksExecutor.execute (Newmergerunnable ());    Executor.shutdown (); }}/*** Download Thread*/classDownloadrunnableImplementsRunnable {Private FinalCountdownlatch donesignal; Private Final inti; Downloadrunnable (Countdownlatch donesignal,inti) { This. donesignal =donesignal;  This. i =i; }     Public voidrun () {dodownload (i);    Donesignal.countdown (); }    Private voidDodownload (inti) {System.out.println ("Thead:" + i + "Download Complete"); }}/*** Merge Threads*/classMergerunnableImplementsrunnable{@Override Public voidrun () {domerge (); }        Private voidDomerge () {System.out.println ("Merge Threads Complete Merge"); }    }

Threading Tool Class-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.