Java concurrent Programming-latching

Source: Internet
Author: User

A latch is a synchronizer (Synchronizer) that can delay the progress of a thread until the thread reaches the terminating state, and Countdownlatch is a flexible latching implementation:
1) allows one or more threads to wait for an event set to occur, and the state of the lockout includes a counter, initialized to a positive number, to implement the count of events that need to wait.
2) Countdown the counter to reduce the operation, indicating that an event has occurred, while the await method waits for the counter to reach 0, at this time all the events that need to wait have occurred.
3) If the entry value of the counter is nonzero, the await will block until the counter is 0, or wait for the thread to break and time out.

[Java]public long timetasks (int nthreads, final Runnable task) throws interruptedexception {final Countdownlatch Startgate = new Countdownlatch (1), final countdownlatch endgate = new Countdownlatch (nthreads); for (int i = 0; i < Nthre Ads i++) {Thread t = new Thread () {public void run () {try {startgate.await (); try {task.run ();} finally {Endgate.countdown ();} } catch (Interruptedexception ignored) {}}};t.start ();} Long start = System.nanotime (); Startgate.countdown (); endgate.await (); Long end = System.nanotime (); return end-start;} [/java]

Latch-a Latch is A synchronizer so can delay the progress of threads until it reaches its terminal state. A latch acts as a gate:until the latch reaches the terminal state the gate was closed and no thread can pass, and in the T Erminal state the gate opens, allowing all threads to pass. Once the latch reaches the terminal state, it cannot change state again, so it remains open forever. Latches can used to ensure, that certain activities does not proceed until other one-time activities complete.

Java concurrent Programming-latching

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.