54

タスクを使用してを返すExecutorServiceことができるのでsubmit、タスクをラップしてメソッドを使用する必要があるのはなぜですか? どちらも同じことをしていると感じます。CallableFutureFutureTaskCallableexecute

4

6 に答える 6

47

FutureTask このクラスはbase implementation of Future、計算を開始およびキャンセルするメソッドを備えた を提供します。

未来はインターフェース

于 2011-02-10T12:10:43.793 に答える
26

実際、あなたは正しいです。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 インスタンスへの参照が複数存在する可能性がないことを確認するためです。つまり、Executorがこのインスタンスを所有しています。

于 2011-02-10T12:09:22.757 に答える
16

Future単なるインターフェースです。舞台裏での実装はFutureTask.

手動で絶対に使用できますが、使用する利点(スレッドのプーリング、スレッドの制限など)FutureTaskが失われます。Executor使用法は、古いものを使用してrunメソッドを使用FutureTaskする場合と非常に似ています。Thread

于 2011-02-10T12:06:41.963 に答える
8

FutureTask を使用する必要があるのは、後でその動作を変更したり、その Callable にアクセスしたりする場合のみです。99% の用途では、Callable と Future を使用してください。

于 2011-02-10T12:07:56.480 に答える