概述
Future 表示异步计算的结果。提供了方法来检查计算是否完成,等待它的完成,并检索计算的结果。只有在计算完成时才能使用 get 方法检索结果,如果必要,会阻塞直到准备就绪。取消由 cancel 方法执行。还提供了其他方法来确定任务是正常完成还是被取消。一旦计算完成,就不能取消计算。如果您希望使用 Future 仅为了可取消性,但不提供可用的结果,则可以声明 Future<?> 类型,并将 null 作为基础任务的结果返回。
public interface Future<V> {
/**
尝试取消此任务的执行。如果任务已经完成或已取消,或由于其他原因无法取消,则此方法无效。否则,如果调用 cancel 时这个任务尚未开始,则此任务不应该运行。如果任务已经开始,则 mayInterruptIfRunning 参数确定是否在尝试停止任务时中断执行此任务的线程(实现知道时)。
此方法的返回值不一定表示任务是否已被取消;使用 isCancelled。
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* Returns {@code true} if this task was cancelled before it completed
* normally.
*
* @return {@code true} if this task was cancelled before it completed
*/
boolean isCancelled();
/**
如果此任务已完成,则返回 true。完成可能是由于正常终止、异常或取消——在这些情况下,此方法都会返回 true。
返回:
如果此任务已完成,则返回 true
*/
boolean isDone();
/**
如果需要,等待计算完成,然后检索其结果。
返回:
计算出的结果
*/
V get() throws InterruptedException, ExecutionException;
/**
和get()一样 并设置超时等待时间
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
分享到: