Java中的Future和FutureTask有什么区别? [英] What's the difference between Future and FutureTask in Java?

查看:431
本文介绍了Java中的Future和FutureTask有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于使用 ExecutorService 可以提交 a 可调用任务并返回 Future ,为什么需要使用 FutureTask 来包装 Callable 任务并使用方法执行?我觉得他们都做同样的事情。

Since use ExecutorService can submit a Callable task and return a Future, why need to use FutureTask to wrap Callable task and use the method execute? I feel they both do the same thing.

推荐答案

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

In fact you are correct. The two approaches are identical. You generally don't need to wrap them yourself. If you are, you're likely duplicating the code in 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()方法:

The only difference between Future and RunnableFuture, is the run() method:

/**
 * 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实例不存在多个引用存在的可能方法。也就是说,执行者拥有这个实例。

A good reason to let the Executor construct the FutureTask for you is to ensure that there is no possible way more than one reference exists to the FutureTask instance. That is, the Executor owns this instance.

这篇关于Java中的Future和FutureTask有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆