Java Executors cancel a task in an executor

Introduction

To cancel a task sent to the executor, use the cancel() method of Future.



import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Task implements Callable<String> {
  @Override/*www. j a  v a  2 s  .  co  m*/
  public String call() throws Exception {
    while (true) {
      System.out.println("Task: Test\n");
      Thread.sleep(100);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    Task task = new Task();
    System.out.println("Main: Executing the Task\n");
    Future<String> result = executor.submit(task);
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.printf("Main: Cancelling the Task\n");
    result.cancel(true);
    System.out.printf("Main: Cancelled: %s\n", result.isCancelled());
    System.out.printf("Main: Done: %s\n", result.isDone());

    executor.shutdown();
    System.out.printf("Main: The executor has finished\n");
  }

}



PreviousNext

Related