Coutdownlatch Multithreaded Synchronization Helper Classes

Source: Internet
Author: User

Countdownlatch, a synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.

Main methods

public Countdownlatch (int count);

public void Countdown();

public void await() throws Interruptedexception

The constructor method parameter specifies the number of times the count

Countdown method, the current thread calls this method, then the count is reduced by one

Awaint method, calling this method will block the current thread until the value of the timer is 0

Example

public class Countdownlatchdemo {
Final static SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
public static void Main (string[] args) throws Interruptedexception {
Countdownlatch latch=new Countdownlatch (2);//Collaboration of two workers
Worker worker1=new worker ("Zhang San", latch);
Worker worker2=new worker ("Li Si", 8000, latch);
Worker1.start ();//
Worker2.start ();//
Latch.await ();//wait for all workers to finish the work
System.out.println ("All work done at" +sdf.format (new Date ()));
}


Static class Worker extends thread{
String Workername;
int worktime;
Countdownlatch latch;
Public Worker (String workername, int worktime, Countdownlatch latch) {
This.workername=workername;
This.worktime=worktime;
This.latch=latch;
}
public void Run () {
System.out.println ("Worker" +workername+ "do-work-begin at" +sdf.format (new Date ()));
DoWork ();//Work
System.out.println ("Worker" +workername+ "Do Work Complete at" +sdf.format (new Date ()));
Latch.countdown ();//workers finish work, counter minus one

}

private void DoWork () {
try {
Thread.Sleep (Worktime);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}


}

Coutdownlatch Multithreaded Synchronization Helper Classes

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.