Java中的Future和FutureTask有什么区别?

Hes*_*sey 49 java callable executorservice futuretask

由于使用ExecutorServicesubmit一个Callable任务并返回Future,为什么需要使用FutureTask包装Callable的任务和使用的方法execute?我觉得他们都做同样的事情.

fmu*_*car 41

FutureTask 该类提供了一个base implementation of Future启动和取消计算的方法

未来就是界面


Mar*_*ouf 26

事实上你是对的.这两种方法是相同的.您通常不需要自己包装它们.如果是,您可能会复制AbstractExecutorService中的代码:

/**
 * Returns a <tt>RunnableFuture</tt> for the given callable task.
 *
 * @param callable the callable task being wrapped
 * @return a <tt>RunnableFuture</tt> which when run will call the
 * underlying callable and which, as a <tt>Future</tt>, will yield
 * the callable's result as its result and provide for
 * cancellation of the underlying task.
 * @since 1.6
 */
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}
Run Code Online (Sandbox Code Playgroud)

Future和RunnableFuture之间的唯一区别是run()方法:

/**
 * A {@link Future} that is {@link Runnable}. Successful execution of
 * the <tt>run</tt> method causes completion of the <tt>Future</tt>
 * and allows access to its results.
 * @see FutureTask
 * @see Executor
 * @since 1.6
 * @author Doug Lea
 * @param <V> The result type returned by this Future's <tt>get</tt> method
 */
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
Run Code Online (Sandbox Code Playgroud)

让Executor为您构造FutureTask的一个很好的理由是确保FutureTask实例不存在多个引用.也就是说,Executor 拥有这个实例.


nan*_*nda 16

Future只是界面.在幕后,实施是FutureTask.

你绝对可以FutureTask手动使用,但你将失去使用Executor(池化线程,限制线程等)的优势.使用FutureTask与使用旧的Thread和使用run方法非常相似.

  • FutureTask同时实现了Future&lt;V&gt;和Runnable,为什么不能提交给ExecutorService呢? (2认同)

Pet*_*rey 7

如果要更改其行为或稍后访问其Callable,则只需要使用FutureTask.对于99%的用途,只需使用Callable和Future.