Saturday, 8 March 2014

IsDone() : Check completion status of task

boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

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

public class CallableTask implements Callable{
 String name;

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

 public String call(){
  try{
   System.out.println(name +" Started Executing");
   System.out.println(name +" Finishes Execution");
  }
  catch(Exception e){
   System.out.println("Task Interrupted " + e);
  }
  return (new Date() + " :: " + name);
 }
}

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

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

  CallableTask task1 = new CallableTask("task1");
  Future<String> f1 = exec.submit(task1);
  Thread.sleep(1000);
  System.out.println("is the task finished " + f1.isDone());
  exec.shutdown();
 }
}
  
Output
task1 Started Executing
task1 Finishes Execution
is the task finished true
  
ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
Statement creates a thread pool of 3 threads.

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




Cancel task exection                                                 Cancellation status of the task                                                 Home

No comments:

Post a Comment