Monday, April 15, 2013

Simple Java Demo to show how to wait threads to finish

Here is a small program that illustrate how to use CountDownLatch to wait Java threads to finish. The example is self-explanatory.
    

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * small demo to use CountDownLatch to wait for multiple threads to finish   
 * 
 * @author stones333
 *
 */
public class FixedThreadPool {

 private CountDownLatch countDownLatch=null;
 
 /**
  * 
  * @param count
  */
    public void startParallelWork(int count) {
        ExecutorService executorService = Executors.newFixedThreadPool( count );
 
        countDownLatch=new CountDownLatch(count); 
        for (int i = 0; i < count; i++) {
            Worker worker = new Worker(this.countDownLatch, i); 
            executorService.execute(worker);
        }
        executorService.shutdown();
    }

    /**
     * 
     * @throws InterruptedException
     */
    public void waitForThreadstoFinish() throws InterruptedException {
    
     System.out.println("START WAITING");
     if (countDownLatch!=null) {
      countDownLatch.await();
     }
     System.out.println("DONE WAITING");
    }

    
    static public class Worker implements Runnable {
     private CountDownLatch countDownLatch;
     private int sleepTime;
     
     
     /**
      * 
      * @param countDownLatch
      * @param sleepTime in second
      */
        public Worker(CountDownLatch countDownLatch, int sleepTime) {
   super();
   this.countDownLatch = countDownLatch;
   this.sleepTime = sleepTime;
  }



  @Override
        public void run() {
         
         System.out.println("Start-" + Thread.currentThread().getName());
         try {
    Thread.sleep( (long) sleepTime * 1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
         System.out.println("End-" + Thread.currentThread().getName());
         if (this.countDownLatch!=null) {
          this.countDownLatch.countDown();
         }
        }

    }

    public static void main(String[] args) throws Exception {
     FixedThreadPool fixedThreadPool = new FixedThreadPool();
     fixedThreadPool.startParallelWork(10);
     fixedThreadPool.waitForThreadstoFinish();
    }
}

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete