Java Thread Synchronization helper class Countdownlatch

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.

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, consider using CyclicBarrier .

CountDownLatchis a universal synchronization tool, it has many uses. Initializes a count of 1 CountDownLatch 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.

CountDownLatchA useful feature is that it does not require countDown the thread that invokes the method to wait until the count arrives 0 o'clock, and before all threads can pass, it simply prevents any thread from continuing through one await .

ImportJava.util.Random;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Countdown Countdownlatch *@authorDuwenlei **/ Public classCountdownlatchtest { Public Static voidMain (string[] args) {Executorservice service=Executors.newcachedthreadpool (); FinalCountdownlatch Sublatch =NewCountdownlatch (1);//Athlete's        FinalCountdownlatch Mainlatch =NewCountdownlatch (3);//Referee's Counter         for(inti = 0; I < 3; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Thread" +thread.currentthread (). GetName () + "Ready to stand by");    Sublatch.await (); //The athlete waits for the referee to send a passwordSYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "command already received"); Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "thread completed");//have run outMainlatch.countdown ();//notify the referee}Catch(interruptedexception e) {e.printstacktrace ();            }                }            };        Service.execute (runnable); }                Try{Thread.Sleep (NewRandom (). Nextint (10000)); System.out.println ("Thread" +thread.currentthread (). GetName () + "outgoing command");//send a password, 3 threads start runningSublatch.countdown ();//counter minus oneSystem.out.println ("Thread" +thread.currentthread (). GetName () + "Waiting for results");//wait for the result after the password is issuedMainlatch.await ();//waiting for all to run outSystem.out.println ("Thread" +thread.currentthread (). GetName () + "All responses received"); } Catch(interruptedexception e) {e.printstacktrace ();    } service.shutdown (); }    }

Java Thread Synchronization helper class Countdownlatch

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.