Synchronization helper Classes:
Countdownlatch is a synchronous helper class that is introduced in Jdk5, which allows one or more threads to wait for another thread to finish before executing.
Implementation principle:
The Countdownlatch is implemented by means of counters, where the initial value of the counter is the number of threads. Each time a thread finishes its task, it reduces the counter by 1, and when the counter has a value of 0 o'clock, indicating that all threads have completed the task, waiting for the line friend on the latch to continue executing, thus achieving the purpose of waiting for the other thread to finish the task.
Countdownlatch Main methods:
Countdownlatch is specifically implemented by Synchronizer, using the AQS state to represent the count:
/** * Synchronization control for Countdownlatch. * Uses AQS state to represent count. */ private static final class Sync extends Abstractqueuedsynchronizer { private static final long Serialversionui D = 4982264981922014374L; Sync (int count) { setState (count); } int GetCount () { return getState (); } protected int tryacquireshared (int acquires) { return (getState () = = 0)? 1:-1; } protected Boolean tryreleaseshared (int releases) { //decrement count; signal when transition to zero for (;;) { int c = getState (); if (c = = 0) return false; int NEXTC = c-1; if (Compareandsetstate (c, NEXTC)) return NEXTC = = 0 ; }} Private final sync sync;
1. Constructor function
public Countdownlatch (int count) { if (count < 0) throw new IllegalArgumentException ("Count < 0"); This.sync = new sync (count); }
Creates a countdownlatch by passing in a numeric value indicating the number of times a thread can recover from a wait state and the countdown method must be called
2. Countdown method
public void Countdown () { sync.releaseshared (1); }
The thread calls this method to subtract 1 from count. When Count is originally 0, this method does nothing, and when count is greater than 0, call this method to subtract 1 when new count is 0, releasing all waiting threads.
3. Await method
(1) Without parameters
public void await () throws Interruptedexception { sync.acquiresharedinterruptibly (1); }
When this method is called, when Count is 0, returns true directly, when Count is greater than 0, the thread waits until the value of Count becomes 0, or the thread is interrupted (interepted, which throws an interrupt exception).
(2) with parameters
Public boolean await (long timeout, timeunit unit) throws Interruptedexception { return Sync.tryacquiresharednanos (1, Unit.tonanos (timeout)); }
When this method is called, when Count is 0, returns True when Count is greater than 0, the thread waits for a period of time, if the value of count changes to 0, returns True when the wait time is exceeded, or if the wait time thread is interrupted, the interrupt exception is thrown.
Countdownlatch Practice
The driver and the worker must wait until the driver comes to load the car, and the driver must wait until all the workers have loaded the goods into the car before driving away.
Worker class:
public class Worker implements Runnable { private String workercode; Private Countdownlatch Startlatch; Private Countdownlatch latch; Worker (Countdownlatch startlatch, Countdownlatch latch, String workercode) { this.startlatch = Startlatch; This.latch = latch; This.workercode = Workercode; } public void Run () { try { startlatch.await (); DoWork (); Latch.countdown (); } catch (Interruptedexception e) { e.printstacktrace (); } } private void DoWork () { System.out.println ("Worker" + Workercode + "is loading goods ...");}
Driver class:
public class Driver {public static void Main (string[] args) throws interruptedexception { Countdownlatch Startla tch = new Countdownlatch (1); Countdownlatch latch = new Countdownlatch (ten); Executorservice executor = Executors.newfixedthreadpool (ten); for (int i=0; i<10; i++) { Executor.execute (new Worker (Startlatch, latch, "worker" + i)); } System.out.println ("Driver are here."); Startlatch.countdown (); System.out.println ("Workers get to work."); Latch.await (); System.out.println ("Driver is ready to go."); Executor.shutdown (); }}
Operation Result:
Driver is here. Workers get to work. Worker Worker0 is loading goods ... Worker Worker1 is loading goods ... Worker Worker2 is loading goods ... Worker Worker3 is loading goods ... Worker worker4 is loading goods ... Worker Worker5 is loading goods ... Worker Worker7 is loading goods ... Worker Worker9 is loading goods ... Worker Worker8 is loading goods ... Worker Worker6 is loading goods ... Driver is ready to go.
For complete engineering Code, please refer to Git:https://github.com/xuweijian/countdownlatch.git
Interpreting Java Synchronization Class Countdownlatch