Getting Started with Countdownlatch thread synchronization in Java

Source: Internet
Author: User

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.

Two inverted-count latches are used below: one to wait for the other to complete

Import Java.util.concurrent.countdownlatch;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Countdownlatchtest {/** * @param args */public static void main (string[] args        ) {Executorservice ThreadPool = Executors.newcachedthreadpool ();        Final Countdownlatch Cdorder = new Countdownlatch (1);        Final Countdownlatch cdanswer = new Countdownlatch (3);          for (int i=0;i<3;i++) {Runnable Runnable = new Runnable () {@Override public void run () { try {System.out.println ("thread" + thread.currentthread (). GetName () + "waiting to accept Command"); cdorder.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "accepted command"); Thread.Sleep ((Long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "response command, process result"); Cdanswer.countdown ();     catch (Interruptedexception e) {e.printstacktrace ();}     }     };        Threadpool.execute (runnable); try {thread.sleep (long) Math.raNdom () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Waiting to publish Command"); Cdorder.countdown (); cdanswer.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "command issued, waiting for results"); System.out.println ("All commands are processed");}       catch (Interruptedexception e) {e.printstacktrace ();} Threadpool.shutdown ();}}



Getting Started with Countdownlatch thread synchronization in Java

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.