Java中的Future和FutureTask有什么区别?
问题内容:
既然使用一个任务ExecutorService
可以返回一个,为什么需要使用包装任务和使用方法?我觉得他们都做同样的事情。submit``Callable``Future``FutureTask``Callable``execute
问题答案:
其实你是对的。两种方法是相同的。通常,您不需要自己包装它们。如果是这样,您可能会在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();
}
让执行者为您构造FutureTask的一个很好的理由是,确保对FutureTask实例的引用不止一种。也就是说,执行者 拥有 这个实例。