Java Executors control a task finishing in an executor

Introduction

The FutureTask class method done() allows you to execute some code after the finalization of a task.

It can be used to make some post-process operations.

This method is called by the FutureTask class.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

class ResultTask extends FutureTask<String> {
  private String name;

  public ResultTask(Callable<String> callable) {
    super(callable);
    this.name = ((ExecutableTask) callable).getName();
  }//from  w  ww . j a  v a 2 s  .co m

  @Override
  protected void done() {
    if (isCancelled()) {
      System.out.println("cancelled:"+ name);
    } else {
      System.out.println("finished"+name);
    }
  }
}

class ExecutableTask implements Callable<String> {
  private String name;

  public ExecutableTask(String name) {
    this.name = name;
  }

  @Override
  public String call() throws Exception {
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
    }
    return "Hello, world. I'm " + name;
  }

  public String getName() {
    return name;
  }
}

public class Main {
  public static void main(String[] args) {
    ExecutorService executor = (ExecutorService) Executors.newCachedThreadPool();
    ResultTask resultTasks[] = new ResultTask[5];
    for (int i = 0; i < 5; i++) {
      ExecutableTask executableTask = new ExecutableTask("Task " + i);
      resultTasks[i] = new ResultTask(executableTask);
      executor.submit(resultTasks[i]);
    }
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }
    for (int i = 0; i < resultTasks.length; i++) {
      resultTasks[i].cancel(true);
    }
    for (int i = 0; i < resultTasks.length; i++) {
      try {
        if (!resultTasks[i].isCancelled()) {
          System.out.println(resultTasks[i].get());
        }
      } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
      }
    }
    executor.shutdown();
  }
}



PreviousNext

Related