Sunday, 9 March 2014

Submit : Runnable task and Get result

<T> Future<T> submit(Runnable task, T result)
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return the given result upon successful completion.

public class RunnableTask implements Runnable {
 String name;

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

 public void run(){
  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);
  }
 }
}

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>());

  RunnableTask task1 = new RunnableTask("task1");
  Future<String> f1 = exec.submit(task1, "Task1 Execution Finished");
  System.out.println(f1.get());
  exec.shutdown();
 }
}
   
Output
task1 Started Executing
task1 Finishes Execution
Task1 Execution Finished

As you observe the output, f1.get(), returns the string 'ask1 Execution Finished', which is passed as a parameter to submit method of ExecutorService Object 'exec.submit(task1, "Task1 Execution Finished")'.

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(task1, "Task1 Execution Finished");
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the run method of the Runnable Object. Once the task is finished the result “ Task1 Execution Finished” is returned to the Future Object.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment