Java Multithreading--Countdownlatch latching

Source: Internet
Author: User

Countdownlatch a synchronous helper class that allows one or more threads to wait until a set of operations that are executing in another thread is completed.
Latching can delay the progress of a thread until it reaches the terminating state, and latching can be used to ensure that certain activities continue until other activities are completed:

    1. Ensure that a calculation does not continue until all the resources it needs are initialized;
    2. Ensure that a service is started after all other services it relies on have been started;
    3. Wait until all participants in an operation are ready before proceeding.
 PackageCom.company;ImportJava.util.concurrent.CountDownLatch;/** Countdownlatch: Latching, in the completion of certain operations, only the operation of all other threads is complete, the current operation continues to execute*/ Public classTestcountdownlatch { Public Static voidMain (string[] args) {FinalCountdownlatch latch =NewCountdownlatch (50); Latchdemo LD=NewLatchdemo (latch); LongStart =System.currenttimemillis ();  for(inti = 0; I < 50; i++) {            NewThread (LD). Start (); }        Try{latch.await (); } Catch(Interruptedexception e) {}LongEnd =System.currenttimemillis (); System.out.println ("Time-consuming:" + (End-start)); }}classLatchdemoImplementsRunnable {PrivateCountdownlatch latch;  PublicLatchdemo (Countdownlatch latch) { This. Latch =latch; } @Override Public voidrun () {Try {             for(inti = 0; I < 50000; i++) {                if(i% 2 = = 0) {System.out.println (i); }            }        } finally{latch.countdown (); }    }}

Results:

A bit longer to intercept the second half of the paragraph bar:

499944999649998 Time-consuming:7301

Java Multithreading--Countdownlatch latching

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.