Countdownlatch latching is also a Synchronizer based on the AQS implementation, which means "all threads wait until the lock is open to continue". Unlike Semaphore's semantics, Semaphore's acquisition and release operations modify state, which may allow itself or another thread to get the lock immediately. The latching operation only determines whether the state is 0, does not modify the state itself, and the latching release modifies the state, decreasing by 1 at a time until the state is 0.
So normally, the latching acquisition is just waiting, not immediately getting the lock, until the release operation turns the state to 0.
Latching can be used to implement many scenarios, such as:
1. A service that relies on the startup of other services to start will allow the service to wait on the lockout of other service states
2. A game must wait for all the ready to arrive to start the game
3. Start a set of related threads
4. Wait for a group of related threads to end
Take a look at Countdownlatch's code. It also provides an internal class of sync to inherit Aqs
1. Countdownlatch can allow multiple threads to enter the critical section at the same time, so it is also a shared mode Aqs
2. The get operation only determines whether the state is 0, that is, whether the wait can be ended, enter the critical section
3. The release operation is a decrease in the status of 1, so called Countdown, similar to the meaning of a count
Private static final class Sync extends Abstractqueuedsynchronizer { private static final long Serialversionuid = 4982 264981922014374L; 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;}}
Countdownlatch maintains a state that represents the total number of counts, releasing the number minus 1 until 0, and its Tryxxx method passes a parameter that has no practical meaning, just to accommodate the interface.
If the acquisition fails, it enters the Aqs wait until the wait is over, releasing the thread in the Aqs queue in a shared manner.
Countdownlatch Common methods are two: await () and Countdown ()
public Countdownlatch (int count) { if (count < 0) throw new IllegalArgumentException ("Count < 0"); This.sync = new sync (count); } Waiting is equivalent to getting the operation public void await () throws Interruptedexception {sync.acquiresharedinterruptibly (1); }//wait for public boolean await (long timeout, timeunit unit) throws Interruptedexception {return Sync.tryacqui Resharednanos (1, Unit.tonanos (timeout)); }public void Countdown () {sync.releaseshared (1); }
Design 1 Test Cases to test the function of Countdownlatch latching
1. Create 1 Two-yuan latching startlatch, only 1 and 2 states, i.e. only once countdown () can open the latch. This startlatch is used to block threads until the main thread says it can start.
2. Create 1 Endlatch with status N, the thread executes the call once countdown, the main thread is blocked in Endlatch until N threads are executed countdown (), the main line friend print end
Package Com.zc.lock;import Java.util.concurrent.countdownlatch;public class Countdownlatchusecase {private int Nthreads;private countdownlatch startlatch;private countdownlatch endlatch;public CountDownLatchUsecase (int n) { This.nthreads = N;startlatch = new Countdownlatch (1); endlatch = new Countdownlatch (nthreads);} public void Race () throws interruptedexception{System.out.println ("Thread" + thread.currentthread (). GetName () + "Is waiting the resource"); Startlatch.await (); System.out.println ("Thread" + thread.currentthread (). GetName () + "got the Resource"); Endlatch.countdown (); } public void Start () {Startlatch.countdown ();} public void End () throws interruptedexception{endlatch.await ();} public static void Main (string[] args) throws exception{final countdownlatchusecase usecase = new Countdownlatchusecase (1 0); for (int i = 0; i < i++) {thread t = new Thread (new Runnable () {@Override Public VoiD run () {try {usecase.race ();} catch (Interruptedexception e) {e.printstacktrace ();} }}, String.valueof (i)); T.start (); } thread.sleep (3000); System.out.println ("Now start!!!"); Usecase.start (); Usecase.end (); System.out.println ("All Thread finished"); }}
Test Result: All threads wait until the main thread says start. After all the threads have executed countdown (), the mainline friend says end
Thread 0 is waiting the Resourcethread 2 is waiting the Resourcethread 3 are waiting the Resourcethread 1 is waiting the RE Sourcethread 4 is waiting the Resourcethread 5 are waiting the Resourcethread 6 is waiting the Resourcethread 7 is waiting The Resourcethread 8 is waiting the Resourcethread 9 is waiting the Resourcenow start!!! Thread 0 got the Resourcethread 2 got the Resourcethread 3 got the Resourcethread 8 got the Resourcethread 7 got the Resou Rcethread 6 got the Resourcethread 5 got the Resourcethread 1 got the Resourcethread 4 got the Resourcethread 9 got the RE Sourceall Thread finished
Talk about high concurrency (26) parsing java.util.concurrent each component (eight) understanding Countdownlatch latching