タスクを使用してを返すExecutorService
ことができるのでsubmit
、タスクをラップしてメソッドを使用する必要があるのはなぜですか? どちらも同じことをしていると感じます。Callable
Future
FutureTask
Callable
execute
6 に答える
FutureTask
このクラスは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 インスタンスへの参照が複数存在する可能性がないことを確認するためです。つまり、Executorがこのインスタンスを所有しています。
Future
単なるインターフェースです。舞台裏での実装はFutureTask
.
手動で絶対に使用できますが、使用する利点(スレッドのプーリング、スレッドの制限など)FutureTask
が失われます。Executor
使用法は、古いものを使用してrunメソッドを使用FutureTask
する場合と非常に似ています。Thread
FutureTask を使用する必要があるのは、後でその動作を変更したり、その Callable にアクセスしたりする場合のみです。99% の用途では、Callable と Future を使用してください。