interface Future<V> 可以对具体的Runnable或Callable任务的进行取消、查询是否完成、获取结果等操作。
boolean cancel(boolean mayInterruptIfRunning);尝试取消任务的执行。在以下情况中尝试会失败:任务已经执行完,已经被取消,或由于某些原因不能取消。如果尝试成功且当cancel被调用时任务尚未启动,任务将不会运行;如果任务已经启动,cancel的入参mayInterruptIfRunning决定了执行中的任务是否应当在尝试终止时被打断。cancel返回后调用isDone会返回true,如果cancel返回true则isCancelled也为true。
入参mayInterruptIfRunning 如果任务正在执行,则会被打断,否则,正在进行中的任务将被允许执行完成。
boolean isCancelled();正常结束前是否被取消。
boolean isDone();正常或异常的终止,取消都会返回true。
V get() throws InterruptedException, ExecutionException;获取执行结果,会阻塞直到任务返回结果。任务取消时抛出CancellationException,任务抛出异常则抛出ExecutionException,当前线程在等待时被中断则抛出InterruptedException。
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; 获取执行结果并指定超时时间,会阻塞直到超时。任务取消时抛出CancellationException,任务抛出异常则抛出ExecutionException,当前线程在等待时被中断则抛出InterruptedException。超时抛出TimeoutException。
FutureTask是Future接口的唯一实现类,实现了Runnable,它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。FutureTask其实是对其属性callable的监控类。callable的状态记录在state属性中,callable的返回结果在outcome中,runner记录运行FutureTask.run方法的线程,waiters记录运行FutureTask.get方法的线程。
private volatile int state; private static final int NEW = 0; private static final int COMPLETING = 1; private static final int NORMAL = 2; private static final int EXCEPTIONAL = 3; private static final int CANCELLED = 4; private static final int INTERRUPTING = 5; private static final int INTERRUPTED = 6; /** The underlying callable; nulled out after running */ private Callable<V> callable; /** The result to return or exception to throw from get() */ private Object outcome; // non-volatile, protected by state reads/writes /** The thread running the callable; CASed during run() */ private volatile Thread runner; /** Treiber stack of waiting threads */ private volatile WaitNode waiters;