Java Concurrency Learning 17--The Thread synchronization tool Countdownlatch

Source: Internet
Author: User

This article is a summary of the study of the article on the network, thank you for your selfless sharing.

A very typical application scenario for Countdownlatch is that there is one task that wants to go down, but it must wait until the other tasks have been completed before proceeding. If we want to continue down the task of calling an await () method for a Countdownlatch object, the other task executes its own task and calls the countdown () method on the same Countdownlatch object, which calls await () The task of the method will block waiting until the count of the Countdownlatch object is reduced to 0.

Package Chapter3;import Java.util.concurrent.countdownlatch;public class videoconference implements Runnable{private Final Countdownlatch controller;public videoconference (int number) {controller = new Countdownlatch (number);} public void arrive (String name) {System.out.println (name+ "have arrived."); Controller.countdown (); System.out.println ("Videoconference:waiting for" +controller.getcount ());} @Overridepublic void Run () {System.out.println ("Videoconference:initialization:" +controller.getcount ()); try { Controller.await (); System.out.printf ("Videoconference:all The participants has come\n"); System.out.printf ("Videoconference:let ' s start...\n");} catch (Interruptedexception e) {e.printstacktrace ();}}}

Package Chapter3;import Java.util.concurrent.timeunit;public class Participant implements Runnable{private Videoconference conference;private String name;public Participant (videoconference conference,string name) { this.conference = Conference;this.name = name;} @Overridepublic void Run () {Long duration = (long) (Math.random () *10); try {TimeUnit.SECONDS.sleep (duration);} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Conference.arrive (name);}}

package chapter3;/** * * <p> * Description:countdownlatch Learning * </p> * @author  Zhangjunshuai * @version 1.0 * Create date:2014-9-25 PM 8:11:55 * Project name:java7thread * * <pre> * modification History: * Date Author Version Description *--- --------------------------------------------------------------------------------------------------------* Lastchange  : $Date:: $ $Author: $ $Rev: $ * </pre> * */public class Main2 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-9-25 pm 8:11:50 * @param args */public static void main (string[] args) {Vi Deoconference conference = new Videoconference (9); Thread threadconference = new Thread (conference); Threadconference.start (); for (int i=0;i<10;i++) {Participant p = new Participant (Conference, "Participant" +i); Thread t = new thread (p); T.start ();}}} 

There are 3 basic elements of the Countdownlatch class:

    1. The initial value determines the number of events that the Countdownlatch class needs to wait.
    2. Await () method, called by the thread waiting for the end of all events.
    3. The countdown () method, which is called after the event has finished executing.

When you create a Countdownlatch object, the object uses the constructor's parameters to initialize the internal counter. Each time the countdown () method is called, the internal counter of the Countdownlatch object is reduced by one. When the internal counter reaches 0, the Countdownlatch object wakes up all the threads that use the await () method to sleep.

It is not possible to reinitialize or modify the value of the internal counter of the Countdownlatch object. Once the value of the counter is initially initialized, the only way to modify it is to use the countdown () method previously used. When the counter reaches 0 o'clock, all calls to the await () method return immediately, and any subsequent calls to the countdown () method will have no effect.

This method differs from the other synchronization methods:

The countdownlatch mechanism is not used to protect shared resources or critical sections. It is used to synchronize one or more threads that perform multiple tasks. It can only be used once. As previously explained, any call to its method is invalid once the Countdownlatch counter reaches 0. If you want to synchronize again, you must create a new object.

The Countdownlatch class has another version of the await () method, which is:

    • Await (long time, timeunit unit): This method sleeps until it is interrupted, the Countdownlatch internal counter reaches 0, or a specific period passes. The Timeunit class contains: Days, HOURS, microseconds, MILLISECONDS, MINUTES, nanoseconds, and SECONDS.

Java Concurrency Learning 17--The Thread synchronization tool Countdownlatch

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.