threads

CountDownLatch example

In this example we shall show you how to use a CountDownLatch. The CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. The CountDownLatch of the example is derscibed below:

  • We have created a class, MyThread that implements the Runnable. It has a CountDownLatch variable and in its constructor it creates a new Thread and causes the thread’s execution calling its start() API method. It overrides the run() API method of Runnable, where in a loop statement it calls the countDown() API method of CountDownLatch. The method decrements the count of the latch, releasing all waiting threads if the count reaches zero.
  • We have created a new CountDownLatch, using CountDownLatch(int count) constructor that constructs a CountDownLatch initialized with the given count.
  • Then we create a new MyThread, using this latch. Calling await() API method of CountDownLatch causes the current thread to wait until the latch has counted down to zero, unless it is interrupted.
  • If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until the count reaches zero due to invocations of the countDown or until some other thread interrupts the current thread,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String args[]) {

  

  CountDownLatch cdl = new CountDownLatch(5);

  new MyThread(cdl);


  try {


cdl.await();

  } catch (InterruptedException exc) {


System.out.println(exc);

  }

  System.out.println("Finish");
    }
}
class MyThread implements Runnable {

    CountDownLatch latch;

    MyThread(CountDownLatch cdl) {

  latch = cdl;

  new Thread(this).start();
    }

    @Override
    public void run() {

  for (int i = 0; i < 5; i++) {


System.out.println(i);


latch.countDown(); 

  }
    }
}

Output:

0
1
2
3
4
Finish

  
This was an example of how to use a CountDownLatch in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button