Follow these steps to implement the example:
- 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);
}
}
- 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) {
- Create a ThreadPoolExecutor object using the newCachedThreadPool() method of the Executors class:
ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors
.newCachedThreadPool();
- Create a new Task object:
Task task=new Task();
- Send the task to the executor using the submit() method:
System.out.printf("Main: Executing the Task ");
Future<String> result=executor.submit(task);
- Put the main task to sleep for 2 seconds:
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
- 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);
- 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());
- 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 ");