Basic usage of Java.util.concurrent.CountDownLatch class

Source: Internet
Author: User

The Java.util.concurrent.CountDownLatch class is a synchronous counter that is constructed with an int parameter, which is the initial value of the counter, each time the countdown () method is called, the counter is reduced by 1, the counter is greater than 0 o'clock, and the await () Method will block the program from continuing execution.
1. The constructor method parameter specifies the number of times the count
2.countDown method, the current thread calls this method, then the count is reduced by one
3.awaint method, calling this method will block the current thread until the value of the timer is 0

Package Cn.baokx;import Java.util.random;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.timeunit;class Subthread implements Runnable{private Countdownlatch downlatch;private String Name;public subthread (countdownlatch downlatch,string name) {This.downlatch = Downlatch;this.name = name;} @Overridepublic void Run () {System.out.println (this.name+ "is working ..."); try {TimeUnit.SECONDS.sleep (New Random (). Nextint (10)); System.out.println (THIS.name + "have finished its working ..."); catch (Interruptedexception e) {e.printstacktrace ();} Finally{this.downlatch.countdown ();}}} public class Countdownlatchtest {public static void main (string[] args) {Countdownlatch downlatch = new Countdownlatch (4); Subthread st1 = new Subthread (Downlatch, "subThread1"); Subthread st2 = new Subthread (Downlatch, "subThread2"); Subthread st3 = new Subthread (Downlatch, "subThread3"); Subthread st4 = new Subthread (Downlatch, "subThread4"); System.out.println ("Mainthread is wating ..."); new Thread (ST1). Start(); new Thread (ST2). Start (); new Thread (ST3). Start (); new Thread (ST4). Start (); try {downlatch.await ();} catch ( Interruptedexception e) {e.printstacktrace ();} System.out.println ("All subthread have finished,mainthread can begin to checking ...");}}


Basic usage of Java.util.concurrent.CountDownLatch class

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.