概要
新しく生成したスレッドの外部操作を可能とするインタフェースである。
非同期のタスクを実行し、その結果を取得やキャンセルするための機能を提供する。
主なメソッド
-
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
:タスクの実行結果を取得する。
指定されたタイムアウト時間内に結果が利用できない場合はTimeoutException
がスローされる。
例
import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Runnable task = () -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Task executed");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Future<?> future = executorService.submit(task);
System.out.println("Task submitted, waiting for the result...");
// タスクの完了を待機
future.get();
System.out.println("Task completed");
executorService.shutdown();
}
}
上記の例では、newSingleThreadExecutor()
メソッドを使用してExecutorService
のインスタンスを作成している。
submit()
メソッドを使用して非同期タスクをスケジュールし、その結果をFuture
オブジェクトとして取得している。
Runnable
を実装したタスクは、2秒間スリープした後に "Task executed" というメッセージを表示する。
get()
メソッドを使用してタスクの完了を待機することで、非同期タスクが完了するまでメインスレッドがブロックされる。
実行結果
Task submitted, waiting for the result...
Task executed
Task completed
この例では、Runnable
を使用して非同期タスクをスケジュールし、その完了を待機している。
補足
上記の例では処理結果を受け取るget
メソッドを使用しているが、タスクを定義しているRunnable
インタフェースのrun
メソッドは、何も受け取らず、何も戻さない。また、例外もスローしない。
Runnableインタフェース
Runnable
は、単一のメソッドであるrun()
メソッドを持ち、引数も戻り値もない。
Runnable
インタフェースは以下のように定義されている。
@FunctionalInterface
public interface Runnable {
void run();
}
run()
メソッドは非常にシンプルなメソッドであり、スレッドが実行する操作を定義する。
Runnable
はスレッドの実行内容を定義するためのインタフェースであり、スレッドの作成と実行に使用される。
引数も戻り値もないため、future().get
を実行すると、スレッドの処理が終了すればnull
が戻される。
もしnull
以外の処理結果を戻したい場合は以下の方法がある。
- オーバーロードされた
submit
メソッドの第2引数に戻り値を指定する。
戻り値の型はFuture
型のパラメータによって決まる。
-
Callable
インタフェースを使用してタスクを定義する。