0
0

More than 1 year has passed since last update.

【JavaGold】Futureインタフェース

Last updated at Posted at 2023-07-17

概要

新しく生成したスレッドの外部操作を可能とするインタフェースである。
非同期のタスクを実行し、その結果を取得やキャンセルするための機能を提供する。

主なメソッド

  • 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インタフェースを使用してタスクを定義する。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0