How to do it...

Follow these steps to implement the example:

  1. Create a class named ExecutableTask and specify that it implements the Callable interface parameterized by the String class:
        public class ExecutableTask implements Callable<String> {
  1. Declare a private String attribute called name. It will store the name of the task. Implement the getName() method to return the value of this attribute:
        private final String name; 
public String getName(){
return name;
}
  1. Implement the constructor of the class to initialize the name of the task:
        public ExecutableTask(String name){ 
this.name=name;
}
  1. Implement the call() method. Put the task to sleep for a random period of time and return a message with the name of the task:
        @Override 
public String call() throws Exception {
try {
long duration=(long)(Math.random()*10);
System.out.printf("%s: Waiting %d seconds for results. ",
this.name,duration);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {}
return "Hello, world. I'm "+name;
}
  1. Implement a class named ResultTask that extends the FutureTask class parameterized by the String class:
        public class ResultTask extends FutureTask<String> {
  1. Declare a private String attribute called name. It will store the name of the task:
        private final String name;
  1. Implement the constructor of the class. It has to receive a Callable object as a parameter. Call the constructor of the parent class and initialize the name attribute using the attribute of the task received:
        public ResultTask(ExecutableTask callable) { 
super(callable);
this.name= callable.getName();
}
  1. Override the done() method. Check the value of the isCancelled() method and write a different message to the console, depending on the returned value:
        @Override 
protected void done() {
if (isCancelled()) {
System.out.printf("%s: Has been canceled ",name);
} else {
System.out.printf("%s: Has finished ",name);
}
}
  1. Implement the main class of the example by creating a class named Main and adding the main() method to it:
        public class Main { 
public static void main(String[] args) {
  1. Create ExecutorService using the newCachedThreadPool() method of the Executors class:
        ExecutorService executor=Executors.newCachedThreadPool();
  1. Create an array to store five ResultTask objects:
        ResultTask resultTasks[]=new ResultTask[5];
  1. Initialize the ResultTask objects. For each position in the array, first you have to create ExecutorTask and then ResultTask using the object. Then, send ResultTask to the executor using the submit() method:
        for (int i=0; i<5; i++) { 
ExecutableTask executableTask=new ExecutableTask("Task "+i);
resultTasks[i]=new ResultTask(executableTask);
executor.submit(resultTasks[i]);
}
  1. Put the main thread to sleep for 5 seconds:
        try { 
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
  1. Cancel all the tasks you have sent to the executor:
        for (int i=0; i<resultTasks.length; i++) { 
resultTasks[i].cancel(true);
}
  1. Write the result of those tasks that haven't been canceled to the console, using the get() method of the ResultTask objects:
        for (int i=0; i<resultTasks.length; i++) { 
try {
if (!resultTasks[i].isCancelled()){
System.out.printf("%s ",resultTasks[i].get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
  1. Finish the executor using the shutdown() method:
            executor.shutdown(); 
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.152.103