Wednesday, August 13, 2014

Simple countdownlatch with callable example

 package com.cisco.my;  
 import java.util.ArrayList;  
 import java.util.concurrent.Callable;  
 import java.util.concurrent.CountDownLatch;  
 import java.util.concurrent.ExecutorService;  
 import java.util.concurrent.Executors;  
 import java.util.concurrent.Future;  
 class MyJob implements Callable<String> {  
      CountDownLatch latch;  
      String threadName;  
      String job;  
      public MyJob(CountDownLatch latch, String threadName, String job) {  
           super();  
           this.latch = latch;  
           this.threadName = threadName;  
           this.job = job;  
      }  
      @Override  
      public String call() throws Exception {  
           // TODO Auto-generated method stub  
           System.out.println(threadName + " Going to sleep");  
           Thread.sleep(5000);  
           System.out.println(threadName + " Awake to sleep");  
           latch.countDown();  
           return job.split(" ")[0];  
      }  
 }  
 public class CountdownLatchExample {  
      private static CountDownLatch latch = new CountDownLatch(10);  
      public static void main(String[] args) {  
           ExecutorService service = Executors.newFixedThreadPool(10);  
           ArrayList<Future<String>> x = new ArrayList<Future<String>>();  
           for (int i = 0; i < 10; i++) {  
                Future<String> fut = service.submit(new MyJob(latch, "Thread " + i,  
                          "Random String to process"));  
                x.add(fut);  
           }  
           try {  
                latch.await();  
           } catch (InterruptedException e) {  
                e.printStackTrace();  
           }  
      }  
 }  

No comments: