java.util.concurrent
public class FutureTask<V> implements RunnableFuture<V>
简介
FutureTask
提供了对Future
的基本实现,可以调用方法去开始和取消一个Callable
,可以查询Callable
是否完成并且获取计算结果。
只有当Callable
完成时才能获取到Callable
结果,一旦计算完成,计算将不能被重启或者被取消
源码分析
AbstractExecutorService.submit(Callable <T> task)(此方法是线程池的执行逻辑):
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
Future:
public interface Future<V> {
//尝试取消当前任务的执行。
//如果任务已经启动,参数mayInterruptIfRunning将决定任务是否应该中断执行该任务的线程,以尝试中断该任务。
boolean cancel(boolean mayInterruptIfRunning);
//如果任务在正常结束之前被被取消返回true
boolean isCancelled();
//正常结束、异常或者被取消导致任务完成,将返回true
boolean isDone();
//等待任务结束,然后获取结果,如果任务在等待过程中被中断将抛出异常
V get() throws InterruptedException, ExecutionException;
//任务最多在给定时间内完成并返回结果,如果没有在给定时间内完成任务将抛出TimeoutException。
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
RunnableFuture:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
FutureTask:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}