Sunday, 9 March 2014

Submit Runnable task

Future<?> submit(Runnable task)
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return null 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 f1 = exec.submit(task1);
  System.out.println("Is the task finished " + f1.get());
  exec.shutdown();
 }
}
   
Output
task1 Started Executing
task1 Finishes Execution
Is the task finished null

As you observe the output, f1.get() returns null, since the task completed successfully.

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(tasks[i])
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.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment