Home  >  Core Java

Example Of CountDownLatch in Java

By Arvind Rai, December 14, 2012
1. CountDownLatch is available in java from jdk 1.5 2. This is used in scenario where multiple threads are working together and a number of threads need to wait until a set of task finished.
3. It works on the basis of a count.
4. Two method await() and countDown() of CountDownLatch performs the basic task.
5. await() method blocks the thread until the count reaches to zero.
6. CountDownLatch can be initialized to one thread or a number of threads (x). With the help of CountDownLatch one threads needs to wait till x threads finishes a task.
package com.concretepage;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
	public static void main(String... args) throws InterruptedException{
	int cnt=10;
	CountDownLatch beginFlag = new CountDownLatch(1);
    CountDownLatch doneFlag = new CountDownLatch(cnt);
    
    for (int i = 0; i < cnt; ++i) 
        new Thread(new Task(beginFlag, doneFlag)).start();

      showMain();            
      beginFlag.countDown(); 
      showMain();  
      doneFlag.await();  
    
	}
	
	public static void showMain(){
		System.out.println("inside main method.");
	}
}

class Task implements Runnable {
	   private final CountDownLatch beginFlag;
	   private final CountDownLatch doneFlag;
	   Task(CountDownLatch beginFlag, CountDownLatch doneFlag) {
	      this.beginFlag = beginFlag;
	      this.doneFlag = doneFlag;
	   }
	   public void run() {
	      try {
	    	  beginFlag.await();
	        show();
	        doneFlag.countDown();
	      } catch (InterruptedException ex) {}
	   }

	   void show() { 
		System.out.println("inside task.");   
	   }
	 }
The thread Task has been started with 10 numbers. But they have not started to run because there is await() method inside task class. Now in main method showMain() method is called. And now with help of countDown(), a signal is sent to run all threads.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us