FutureTask 类提供了一个名为 done() 的方法,允许您在任务在一个执行者中执行结束后还能执行某些代码。 可被用于执行某些后处理操作、生成报表、通过邮件发送结果或释放某些资源。 当此 FutureTask 对象控制的任务结束时,done() 方法由 FutureTask 类在内部调用。 此方法在设置了任务结果、状态改变成isDone状态后被调用,不管任务是否被取消或正常结束。
默认情况此方法是空的。您可以扩展 FutureTask 类并覆盖实现 done() 方法来改变默认行为。
本节的示例代码在 com.elanzone.books.noteeg.chpt4.sect10 package中
执行任务线程类 : Callable<String> ExecutableTask
private String name; public ExecutableTask(String name) { this.name = name; }
@Override public String call() throws Exception { try { long duration = (long) (Math.random() * 10); System.out.printf("%s: Waiting %d seconds for results.\n", this.name, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { } return "Hello, world. I'm " + name; }
结果处理线程类 : FutureTask<String> ResultTask
private String name; public ResultTask(Callable<String> callable) { super(callable); this.name = ((ExecutableTask) callable).getName(); }
@Override protected void done() { if (isCancelled()) { System.out.printf("%s: Has been canceled\n", name); } else { System.out.printf("%s: Has finished\n", name); } }
控制类 : Main
ExecutorService executor = 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 e) { e.printStackTrace(); } for (int i = 0; i < 5; i++) { resultTasks[i].cancel(true); }
for (ResultTask resultTask : resultTasks) { try { if (!resultTask.isCancelled()) { System.out.printf("%s\n", resultTask.get()); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }
executor.shutdown();