The Countdownlatch of Java concurrent programming

Source: Internet
Author: User

In Java we are provided with a synchronous helper class Countdownlatch, what is this class for? Here's a little bit of learning.

Countdownlatch

A synchronous helper class that runs one or more threads in a wait operation before completing a set of operations that are being performed in another thread.

Initialized with the given count CountDownLatch . Because the method is called countDown() , the await method will remain blocked until the current count reaches 0. After that, all the waiting threads are freed, and await all subsequent calls are returned immediately. This behavior occurs only once-the count cannot be reset. If you need to reset the count.

CountDownLatchUsed as a simple on/Guan, or Portal: countDown() all called await threads are waiting at the entrance until the portal is opened by the calling thread. N is initialized CountDownLatch to allow a thread to wait until the N-Thread completes an operation, or to wait until an operation has finished n the second.

1. Constructors

Determines the number of events that need to wait

2.await ()

Keep all threads in a wait state

3.countDown ()

The counter is reduced by one operation, and when it is 0, all threads are triggered from the hibernation state.


The following is a synchronous example to uncover the veil of Countdownlatch!

Package Com.test;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * @ClassName: Countdownlatchtest * @Description: * The program is used to simulate sending commands and executing commands, the main thread represents the commander, new 3 lines Cheng represents the warrior, the warrior waits for the commander to give orders, and the soldiers must wait if the commander does not give orders. Once the orders were issued, the soldiers went to perform their tasks, the commanders were waiting, the soldiers reported to the commander, and the commanders ended the wait. * @author: LUCKY * @date: January 4, 2016 PM 7:31:06 * * public class Countdownlatchtest {public static void main (String  [] args) {Executorservice service = Executors.newcachedthreadpool ();//Create a thread pool final countdownlatch Cdorder = new Countdownlatch (1);//Commander's command, set to 1, Commander a command, then Cutdown, become 0, the soldiers perform the task final countdownlatch cdanswer = new COUNTDOWNL                Atch (3);//Because there are three warriors, so the initial value is 3, each warrior performs a task Cutdown once, when three are executed and become 0, the commander stops waiting.                    for (int i=0;i<3;i++) {Runnable Runnable = new Runnable () {public void run () { try {System.out.println ("thread" + thread.currentthread (). GetnamE () + "ready to accept command"); Cdorder.await ();                         The soldiers are waiting for the command state System.out.println ("thread" + thread.currentthread (). GetName () +                                                        "Accepted order");                            Thread.Sleep ((Long) (Math.random () *10000));                                                SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "response command processing result"); Cdanswer.countdown ();                                        The mission was completed and returned to the commander, Cdanswer minus 1.                    } catch (Exception e) {e.printstacktrace ();            }                                }            };                    Service.execute (runnable);//Add Task for thread pool} try {Thread.Sleep ((long) (Math.random () *10000));        SYSTEM.OUT.PRINTLN ("Threads" + thread.currentthread (). GetName () + "upcoming Commands");                            Cdorder.countdown ();            Send command, Cdorder minus 1, waiting for the soldiers to stop waiting to go to perform their task.                SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "command sent, waiting for results"); Cdanswer.await ();             After the command is sent the commander is in a wait state, and once Cdanswer is 0 o'clock stop waiting to continue execution System.out.println ("thread" + thread.currentthread (). GetName () +            "All responses have been received");        } catch (Exception e) {e.printstacktrace (); } service.shutdown (); End of task, stop all threads of thread pool}}


The Countdownlatch of Java concurrent programming

Related Article

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.