There are three classes in Java and the package that synchronize the behavior of a batch of threads, namely Countdownlatch, Semaphore, and Cyclicbarrier.
Countdownlatch
Countdownlatch is a counter lockout, the main function is to block the current thread through the await () method, and then wait for the counter to be reduced to 0, and then arouse these threads to continue execution. There are two main methods in this class, one is the method of reducing counter: Countdown (), the core code of the implementation is as follows:
public 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; } }
Very simply, if the current status of 0 is obtained, the lock is finished, returns false directly, if it does not end, and then goes to set the counter minus 1, if the compareandsetstate is unsuccessful, it continues the loop execution. And one of the methods that waits for the counter to be zeroed is await ().
There are a few things you can do with Countdownlatch:
1. Main thread control initiates a set of threads at the same time
Final Countdownlatch count = new Countdownlatch (1), for (int i = 0; i < 3; i++) { new Thread ("thread" + i) { pub LIC void Run () { System.out.println (Thread.CurrentThread (). GetName () + "Wait"); try { count.await (); } catch (Interruptedexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "start"); } . Start ();} Wait three seconds, otherwise there may be 3 threads that do not all have an await state try { thread.sleep (+);} catch (Interruptedexception e) { E.printstacktrace ();} Count.countdown ();
2. The main thread waits for all sub-threads to complete before executing:
Final Countdownlatch count = new Countdownlatch (3), for (int i = 0; i < 3; i++) { new Thread ("thread" + i) { pub LIC void Run () { System.out.println (Thread.CurrentThread (). GetName () + "start"); Count.countdown (); } }. Start ();} try { count.await ();} catch (Interruptedexception e) { e.printstacktrace ();} System.out.println ("All End!!!");
Semaphore
Semaphore and Countdownlatch are similar, the difference is that the value of semaphore can be released after the acquisition, not as Countdownlatch has been reduced to the end. It is also used more to limit the flow, similar to the function of the valve. If some resources are qualified to be accessed by up to n threads, then more than n hosts are not allowed to be accessed again, and when the existing thread ends, it is freed and then the new thread is allowed to come in. A bit like lock with unlock process. In contrast, he has two main methods:
- The Acquire (), which is used to obtain permissions, is similar to the Countdownlatch.countdown ();
- Release (), whose underlying implementation and acquire () is an inverse process for releasing permissions.
Use semaphore to implement the current limit code see: semaphore Example
Cyclicbarrier
Cyclicbarrier is used for a level to block the residence thread, and so when all the threads are executed to the level, then unify the next operation, the most important method is the await () method, which is implemented as follows:
private int Dowait (Boolean timed, Long Nanos) throws Interruptedexception, Brokenbarrierexception, Timeoutexc eption {//Lock to prevent thread unsafe final reentrantlock lock = This.lock at the back of the minus 1 count; Lock.lock (); try {final Generation g = Generation; if (g.broken) throw new Brokenbarrierexception (); if (thread.interrupted ()) {breakbarrier (); throw new Interruptedexception (); }//If the current thread executes, the counter is reduced by 1 and the counter to 0 indicates that all threads are executed here, and the next operation can be called int index =--count; if (index = = 0) {//tripped Boolean ranaction = false; try {//Gets the next operation defined and executes the final Runnable command = Barriercommand; if (command! = null) Command.run (); Ranaction = true; Nextgeneration (); return 0; } finally {if (!ranaction) breakbarrier (); }}//loop until tripped, broken, interRupted, or timed out for (;;) {try {if (!timed) trip.await (); else if (Nanos > 0L) Nanos = Trip.awaitnanos (Nanos); } catch (Interruptedexception IE) {if (g = = Generation &&! G.broken) {BREAKBA Rrier (); throw ie; } else {//we ' re about-to-finish waiting even if we had not//been interrupted, so this interrupt is deemed to//"belong" to subsequent execution. Thread.CurrentThread (). interrupt (); }} if (G.broken) throw new Brokenbarrierexception (); if (g! = generation) return index; If (timed && Nanos <= 0L) {breakbarrier (); throw new TimeoutException (); }}} finally {Lock.unlock (); }}
One benefit of the two classes before this analogy is that it is somewhat similar to slicing programming, which allows us to cut a piece of logic into one slice of a homogeneous thread and synchronize the execution speed of all threads. The
example code is as follows:
Final Cyclicbarrier barrier = new Cyclicbarrier (4, New Runnable () { @Override public void Run () { System.out. println ("All Threads Here");} ); for (int i = 0; i < 4; i++) { new Thread ("thread" + i) {public void run () { System.out.println (Thread.curr Entthread (). GetName () + "Wait"); try { barrier.await (); } catch (Interruptedexception e) { e.printstacktrace (); } catch ( Brokenbarrierexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "crossed"); } }. Start ();}
The resulting output is:
THREAD0 wait
Thread1 wait
Thread2 wait
Thread3 wait
All Threads here
Thread0 crossed
Thread1 crossed
Thread2 crossed
Thread3 crossed
Forwarding---[Sea supplements]java concurrency Countdownlatch, semaphore and Cyclicbarrier