How to do it...

Follow these steps to implement the example:

  1. Create a class named Task and specify that it implements the Callable interface parameterized by the String class. Implement the call() method. Write a message to the console and put it to sleep for 100 milliseconds inside an infinite loop:
        public class Task implements Callable<String> { 
@Override
public String call() throws Exception {
while (true){
System.out.printf("Task: Test ");
Thread.sleep(100);
}
}
  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 a ThreadPoolExecutor object using the newCachedThreadPool() method of the Executors class:
        ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors
.newCachedThreadPool();
  1. Create a new Task object:
        Task task=new Task();
  1. Send the task to the executor using the submit() method:
        System.out.printf("Main: Executing the Task
"); 
Future<String> result=executor.submit(task);
  1. Put the main task to sleep for 2 seconds:
        try { 
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Cancel the execution of the task using the cancel() method of the Future object, named result, returned by the submit() method. Pass the true value as a parameter of the cancel() method:
        System.out.printf("Main: Canceling the Task
"); 
result.cancel(true);
  1. Write the result of a call to the isCancelled() and isDone() methods to the console. This is to verify that the task has been canceled, and hence, already done:
        System.out.printf("Main: Canceled: %s
",result.isCancelled()); 
System.out.printf("Main: Done: %s ",result.isDone());
  1. Finish the executor with the shutdown() method and write a message indicating the finalization of the program:
        executor.shutdown(); 
System.out.printf("Main: The executor has finished ");
..................Content has been hidden....................

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