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