Countdownlatch and cyclicbarrier the difference and usage of the demo

Source: Internet
Author: User

The description inside the Javadoc is like this.

Countdownlatch:a synchronization aid that allows one or more threads to wait until A set of op Erations being performed in other threads completes.

CYCLICBARRIER:A synchronization aid that allows a set of threads to all waitfor each othe R to reach A Common B Arrier Point.

Maybe my english is not good enough, I feel that it is not easy to understand their differences accurately from this javadoc.
My understanding is that

Countdownlatch: One thread (or more) waits for another n thread to complete something before it can be executed.
Cyclicbarrier:n threads wait for each other, as long as any one thread is not complete, and the other N-1 threads must wait.
It should be a little clearer,
For Countdownlatch, the focus is on the " One thread ", which is waiting , and the other n's thread can continue waiting after "something" is done and can terminate .

For Cyclicbarrier, the point is that n threads , either one of them is not finished, and all the threads must wait.

Countdownlatch is the counter, the thread completes one to remember one, just like a count off, just is descending.

And cyclicbarrier more like a sluice , the thread executes like the water, at the gate will be blocked, until the water is full (thread-to-Qi), only to begin to vent the flow.

See many people on the net the difference between Countdownlatch and Cyclicbarrier is simple to understand that Countdownlatch is a one-time, and cyclicbarrier can continue to use after calling reset. Well, if it's just that simple, I think Cyclicbarrier is simply named Resetablecountdownlatch, which is obviously not.
The above is for the purpose of the design to see these two classes.

http://blog.csdn.net/kjfcpua/article/details/7300286

Usage:

First, Countdownlatch usage

The Countdownlatch class is located under the Java.util.concurrent package and can be used to implement similar counter functions. For example, there is a task a, which waits for the other 4 tasks to be executed before they can be executed, and this is done using Countdownlatch.

The Countdownlatch class provides only one constructor:

public Countdownlatch (int count) {}; Parameter count is a count value

Then the following 3 methods are the most important methods in the Countdownlatch class:

public void await () throws interruptedexception {};//The thread that calls the await () method is suspended, it waits until the count value is 0 to continue execution of the public boolean await (long Timeout, Timeunit unit) throws Interruptedexception {};//and await (), just wait a certain amount of time after the count value has not changed to 0 will continue to execute public void Countdown () {}; Subtract the count value by 1

Ii. usage of Cyclicbarrier

It allows a set of threads to wait until a certain state is executed, and then cyclicbarrier can be reused when all waiting threads are freed. Let's call this state barrier, and when the await () method is called, the thread is barrier.

The Cyclicbarrier class is located under the Java.util.concurrent package and Cyclicbarrier provides 2 constructors:

Public Cyclicbarrier (Int. parties, Runnable barrieraction) {} public Cyclicbarrier (int parties) {}

The parameter parties specifies how many threads or tasks to wait for the barrier state, and the parameters barrieraction what will be done when those threads reach the barrier state.

Then the most important method in Cyclicbarrier is the await method, which has 2 overloaded versions:

public int await () throws Interruptedexception, brokenbarrierexception {};p ublic int await (long timeout, timeunit unit) th Rows Interruptedexception,brokenbarrierexception,timeoutexception {};

The first version is more commonly used to suspend the current thread until all threads reach the barrier state and perform subsequent tasks simultaneously;

The second version is to allow these threads to wait for a certain amount of time, and if the thread does not reach the barrier state, then the threads that reach barrier will perform the subsequent tasks directly.

Http://www.cnblogs.com/codeOfLife/p/5687691.html

ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importjava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.CyclicBarrier;ImportJava.util.concurrent.TimeUnit; Public classCyclicbarrierdemo {Private Static FinalLogger Logger = Loggerfactory.getlogger (Cyclicbarrierdemo.class);  Public Static voidMain (string[] args)throwsinterruptedexception {intCount = 4; Countdownlatch startgate=NewCountdownlatch (count); Cyclicbarrier Barrier=NewCyclicbarrier (count);  for(inti = 0; I < count; i++) {thread thread=NewThread (NewWriter (barrier, Startgate), "demo" +i);        Thread.Start (); } TimeUnit.SECONDS.sleep (10);        Startgate.await (); Logger.info (" "); Logger.info (" "); Logger.info ("======countdownlatch up blocking the role of threading ======"); Logger.info (" "); Logger.info (" "); Logger.info ("The reusability of Cyclicbarrier begins:"); Logger.info (" ");  for(inti = 0; I < count; i++) {thread thread=NewThread (NewWriter (barrier, startgate), "Damo" + (i + 4));        Thread.Start (); } logger.info ("The Count of Countdownlatch has been exhausted. does not act as a blocking thread here. "); }    Static classWriterImplementsRunnable {PrivateCyclicbarrier Cyclicbarrier; PrivateCountdownlatch startgate;  PublicWriter (Cyclicbarrier cyclicbarrier, Countdownlatch startgate) { This. Cyclicbarrier =Cyclicbarrier;  This. startgate =startgate; } @Override Public voidrun () {Try{startgate.countdown (); Logger.info ("Thread" + thread.currentthread (). GetName () + "cyclicbarrier.await () before execution, waiting for other threads to finish writing");                Cyclicbarrier.await (); TimeUnit.SECONDS.sleep (5);//sleep a while. This allows you to see the reusability of Cyclicbarrier.await () well in the log.}Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } logger.info (Thread.CurrentThread (). GetName ()+ "cyclicbarrier.await () after execution ..."); }    }}

Output:

[2016-07-24 00:41:25,021] [Demo0] [Cyclicbarrierdemo] Info-thread demo0cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:25,025] [Demo2][cyclicbarrierdemo] INFO- Thread demo2cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:25,032] [Demo1][cyclicbarrierdemo] INFO- Thread demo1cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:25,033] [Demo3][cyclicbarrierdemo] INFO- Thread demo3cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:30,033] [Demo3][cyclicbarrierdemo] INFO- Demo3cyclicbarrier.await () after executing ... [2016-07-24 00:41:30,035] [Demo2] [Cyclicbarrierdemo] Info-demo2cyclicbarrier.await () after executing ... [2016-07-24 00:41:30,035] [Demo0] [Cyclicbarrierdemo] Info-demo0cyclicbarrier.await () after executing ... [2016-07-24 00:41:30,039] [Demo1] [Cyclicbarrierdemo] Info-demo1cyclicbarrier.await () after executing ... [2016-07-24 00:41:35,011] [Main] [Cyclicbarrierdemo] Info-[2016-07-24 00:41:35,011] [Main][cyclicbarrierdemo] Info-[2016-07-24 00:41:35,012] [Main][cyclicbarrierdemo] in FO-======countdownlatch up blocking the role of threads = ===[2016-07-24 00:41:35,012] [Main][cyclicbarrierdemo] Info-[2016-07-24 00:41:35,012] [Main][cyclicbarrierdemo] Info- [2016-07-24 00:41:35,012] [Main] [Cyclicbarrierdemo] Info-cyclicbarrier reusability begins: [2016-07-24 00:41:35,012] [Main][cyclicbarrierdemo] INFO-[2016-07-24 00:41:35,017] [Damo4 ][cyclicbarrierdemo] INFO-Thread damo4cyclicbarrier.await (), waiting for other threads to finish writing [2016-07-24 00:41:35,017] [main][ Cyclicbarrierdemo] The count of Info-countdownlatch has been exhausted. This does not play the role of blocking threads [2016-07-24 00:41:35,017] [Damo6][cyclicbarrierdemo] INFO-thread damo6cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:35,017] [Damo5] [Cyclicbarrierdemo] Info-thread damo5cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:35,017] [Damo7][cyclicbarrierdemo] INFO- Thread damo7cyclicbarrier.await () before execution, waiting for other threads to finish writing [2016-07-24 00:41:40,017] [Damo7][cyclicbarrierdemo] INFO- Damo7cyclicbarrier.await () after executing ... [2016-07-24 00:41:40,017] [Damo6] [Cyclicbarrierdemo] Info-damo6cyclicbarrier.await () after executing ... [2016-07-24 00:41:40,017] [Damo4] [CYCLICBArrierdemo] info-damo4cyclicbarrier.await () after executing ... [2016-07-24 00:41:40,018] [Damo5] [Cyclicbarrierdemo] Info-damo5cyclicbarrier.await () after executing ...

Demo

Countdownlatch and cyclicbarrier the difference and usage of the demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.