Sunday, 9 March 2014

Submit callable task

ExecutorService provides a method to submit a callable task and get the result of the task.

Future<T> submit(Callable<T> task)
Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.

import java.util.concurrent.*;
import java.util.*;

public class CallableTask<String> implements Callable<String>{
 String name;

 CallableTask(String name){
  this.name = name;
 }

 public String call(){
  try{
   System.out.println(name +" Started Executing");
   Thread.sleep(1000);
   System.out.println(name +" Finishes Execution");
  }
  catch(Exception e){
   System.out.println("Task Interrupted " + e);
  }
  return (String)(new Date() + " :: " + name);
 }
}
  
import java.util.concurrent.*;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  CallableTask task1 = new CallableTask("task1");
  Future<String> f1 = exec.submit(task1);
  exec.shutdown();
 }
}
  
Output
task1 Started Executing
task1 Finishes Execution
   
ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Above statement create a thread pool of size 3. So it can run 3 tasks at a time, Since 3 threads are reside in the pool.

exec.submit(tasks1)
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Callable Object.




Wait untill all tasks finish execution                                                 Submit Callable task                                                 Home

No comments:

Post a Comment