Java中Future和FutureTask有什么区别?

2022-08-31 17:32:01

既然可以使用一个任务并返回一个,为什么需要使用来包装任务而使用的方法呢?我觉得他们都在做同样的事情。ExecutorServicesubmitCallableFutureFutureTaskCallableexecute


答案 1

未来任务此类提供了一个 ,其中包含用于启动和取消计算的方法base implementation of Future

未来是接口


答案 2

事实上你是对的。这两种方法是相同的。您通常不需要自己包装它们。如果你是,你可能会复制 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);
}

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();
}

让 Executor 为您构造 FutureTask 的一个很好的理由是为了确保 FutureTask 实例不存在多个引用。也就是说,执行程序拥有此实例。


推荐