Small Example of Java-CountDownLatch

Source: Internet
Author: User

Small Example of Java-CountDownLatch

Content: CountDownLatch allows one or more threads to wait for other threads to complete the operation. The CountDownLatch constructor receives an int type parameter as a counter. If you want to wait for N threads or N execution steps, you can pass N as a parameter. When we call the CountDownLatch countDown method once, N will be reduced by 1, and the await of CountDownLatch will block the current thread until N is 0. When multiple threads are used, you only need to pass the reference of CountDownLatch to the thread.

 

Public class CountDownLatchTest {static class Worker implements Runnable {private final CountDownLatch doneSignal; private final int I; public Worker (CountDownLatch doneSignal, int I) {this. doneSignal = doneSignal; this. I = I ;}@ Overridepublic void run () {System. out. println ("now is" + I); doneSignal. countDown () ;}} public static void main (String [] args) throws InterruptedException {int N = 10; CountDownLatch countDownLatch = new CountDownLatch (N); ExecutorService executor = Executors. newFixedThreadPool (N); for (int I = 0; I <N; I ++) executor.exe cute (new Worker (countDownLatch, I); countDownLatch. await (); System. out. println ("over ");}}


 

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.