Thursday, October 29, 2015

Java ExecutorSerivce Example


public class Problem1 {
 
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "Task #" + mCount.getAndIncrement());
        }
    };
 
 public static void main(String[] args) {
  System.out.println("CORE_POOL_SIZE : "+CORE_POOL_SIZE);
  
  ExecutorService service = Executors.newFixedThreadPool(CORE_POOL_SIZE, sThreadFactory);
  
  service.execute(new Task());
  service.execute(new Task());
  service.execute(new Task());
  service.execute(new Task());
  
  Future<Integer> res1 = service.submit(new Task1());
  Future<Integer> res2 = service.submit(new Task1());
  Future<Integer> res3 = service.submit(new Task1());
  Future<Integer> res4 = service.submit(new Task1());
  try {
   System.out.println("result from callable -> "+res1.get());
   System.out.println("result from callable -> "+res2.get());
   System.out.println("result from callable -> "+res3.get());
   System.out.println("result from callable -> "+res4.get());
  } catch (InterruptedException e) {
   e.printStackTrace();
  } catch (ExecutionException e) {
   e.printStackTrace();
  }
  
  service.shutdown();
 }
 
 static class Task implements Runnable{

  @Override
  public void run() {
   System.out.println("Enter");
   String threadName = Thread.currentThread().getName();
   System.out.println(threadName);
   
   try {
    Thread.sleep(10000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   
   
   System.out.println("Exit");
  }
  
 }
 
 static class Task1 implements Callable<Integer>{

  @Override
  public Integer call() throws Exception {
   System.out.println("Enter");
   String threadName = Thread.currentThread().getName();
   System.out.println(threadName);
   
   Thread.sleep(10000);
   
   System.out.println("Exit");
   return new Random().nextInt(100);
  }
  
 }
}

0 comments:

Post a Comment