First, Introduction
1, Countdownlatch is a synchronization counter, the construction of an int parameter, which is the initial value of the counter, each call Countdown () method, the counter minus 1, the counter is greater than 0 o'clock, the await () method will block the execution of the program. The Countdownlatch can be seen as an inverted-count latch that triggers a specific event when the count is reduced to 0 o'clock. This feature allows the main thread to wait for the end of a child thread.
Countdownlatch the most important method is countdown () and await (), the former is mainly a countdown, the latter is waiting for the countdown to 0, if not reached 0, only blocking wait.
2. Cyclicbarrier is also a synchronous helper class that allows a group of threads to wait until they reach a common barrier point (common barrier points). each time the Wait () method is called, the count is reduced by 1 and the current thread is blocked. When the count is reduced to 0 o'clock, the blocking is lifted, and all the blocked threads on this cyclicbarrier begin to run. After that, if the await () method is called again, the Count becomes N-1 and the new round starts again, so it is called the barrier of the loop.
Second, the use of the scene
1. Countdownlatch can be used to collaborate on a set of threads and another set of threads. For example, there is a task that wants to go down, but it must wait until the other tasks have been completed before you can proceed. If we want to continue to perform the task of invoking an await () method of a Countdownlatch object, the other task executes its own task and calls the countdown () method on the same Countdownlatch object, that call await ( ) method will block the wait until the count of the Countdownlatch object is reduced to 0.
2, Cyclicbarrier need all sub-tasks are completed, only perform the main task, this time you can choose to use Cyclicbarrier.
Countdownlatch applies To work collaboration between a set of threads and another main thread. A main thread waits for the task of a group of workers to complete before continuing its execution is the primary scenario for using Countdownlatch; Cyclicbarrier is used for a group or groups of threads, such as a set of threads that need to agree at a point in time, such as starting a job at the same moment. In addition, the cyclic properties of Cyclicbarrier and the Runnable parameters accepted by the constructors are countdownlatch.
Iii. Common methods
Countdownlatch1. Public voidThe Count of Countdown () decrements the latch, and if the count reaches 0, all waiting threads are freed. If the current count is greater than 0, the count is reduced. If the new count is zero, all waiting threads are re-enabled for thread scheduling purposes. If the current count equals zero, no action occurs. 2. Public BooleanAwaitLongTimeout, timeunit unit)throwsinterruptedexception causes the current thread to wait until the latch is counted down to 0 unless the thread is interrupted or the specified wait time is exceeded. If the current count is zero, this method returns immediatelytruevalues. If the current count is greater than 0, the current thread is disabled for thread scheduling purposes, and the thread will remain dormant until one of the following three situations occurs: The count reaches 0 due to the call to the countdown () method, or some other thread interrupts the current thread, or the specified wait time has been exceeded. If the count reaches 0, the method returnstruevalues. If the current thread: The interrupt state of the thread has been set when entering this method, or if it is interrupted while waiting, the interruptedexception is thrown, and the current thread's interrupted state is cleared. If the specified wait time is exceeded, the return value isfalse. If the time is less than or equal to zero, this method does not wait at all. Parameter: Timeout-The maximum time to wait for unit-the time unit of the timeout parameter. Returns: Returns if the count reaches 0trueIf the wait time is exceeded before the count reaches 0, the returnfalsethrown: interruptedexception-If the current thread is interrupted while waiting
Cyclicbarrier Public intAwait ()throwsinterruptedexception, Brokenbarrierexception waits until all the participants have already barrier the await method. If the current thread is not the last thread that will arrive, it will be disabled for scheduling purposes, and the thread will remain dormant until one of the following occurs: The last thread arrives, or one of the other threads interrupts the current thread, or another thread interrupts another waiting thread, or another thread waits for Barrier time out, or some other thread barrier reset (). If the current thread: The interrupt state of the thread has been set when entering this method, or if it is interrupted while waiting, the interruptedexception is thrown, and the current thread's interrupted state is cleared. Throws a Brokenbarrierexception exception if barrier is reset () when the thread is waiting, or if barrier is corrupted while calling await, or if any of the threads are waiting. If any thread is interrupted while waiting, all other waiting threads will throw a brokenbarrierexception exception and put barrier in a corrupt state. If the current thread is the last thread to arrive, and a non-empty barrier operation is provided in the constructor, the current thread will run the operation until another thread is allowed to continue running. If an exception occurs during the execution of a barrier operation, the exception is propagated to the current thread and the barrier is placed in a corrupt state. Returns: The index of the current thread reached, where Index getparties ()-1indicates the first thread that will arrive, 0 indicates that the last thread to arrive was thrown: interruptedexception-if the current thread is interrupted while waiting brokenbarrierexception-If another thread is interrupted or timed out while the current thread waits, or if barrier is reset, or barrier is corrupted when the await is called, or if the barrier operation (if present) fails because of an exception.
Iv. examples
Let's look at the example in the JDK documentation
1, Countdownlatch
We can imagine the car on the scene of the car repair process, only after the startsignal command issued, the maintenance workers began to work, only after all the workers to complete the work, the car can continue.
classDriver {// ... voidMain ()throwsinterruptedexception {countdownlatch startsignal=NewCountdownlatch (1); Countdownlatch donesignal=NewCountdownlatch (N); for(inti = 0; i < N; ++i)//Create and start threads NewThread (NewWorker (startsignal, donesignal)). Start (); Dosomethingelse (); //don ' t let run yetStartsignal.countdown ();//Let all threads proceedDosomethingelse (); Donesignal.await (); //wait for all to finish }}classWorkerImplementsRunnable {Private FinalCountdownlatch startsignal; Private FinalCountdownlatch donesignal; Worker (Countdownlatch startsignal, Countdownlatch donesignal) { This. startsignal =startsignal; This. donesignal =donesignal; } Public voidrun () {Try{startsignal.await (); DoWork (); Donesignal.countdown (); } Catch(Interruptedexception ex) {}//return; } voiddoWork () {...}}
2, Cyclicbarrier
classSolver {Final intN; Final float[] data; Finalcyclicbarrier Barrier; classWorkerImplementsRunnable {intMyrow; Worker (intRow) {Myrow =Row;} Public voidrun () { while(!Done ()) {Processrow (myrow); Try{barrier.await (); } Catch(Interruptedexception ex) {return; } Catch(Brokenbarrierexception ex) {return; } } } } PublicSolver (float[] matrix) {Data=Matrix; N=matrix.length; Barrier=NewCyclicbarrier (N,NewRunnable () { Public voidrun () {mergerows (...); } }); for(inti = 0; i < N; ++i)NewThread (NewWorker (i)). Start (); Waituntildone (); }}
v. Summary
CountDownLatchis the ability to keep a group of threads waiting for another set of threads to run and run;
CyclicBarrierEnables a set of threads to synchronize at one point in time, starting with all or part of a task together. At the same time, it can be recycled.
Reference: Http://my.oschina.net/lifany/blog/207995?p=2#comments
As I have limited experience, the article will inevitably have errors, please browse the article you correct or have different views to discuss together!
Java concurrency Synchronizer's countdownlatch, Cyclicbarrier