問題一覧に戻る
上級高度な機能
問題111: FutureとCallable
FutureとCallableインターフェースで非同期計算の結果を処理します。並行タスクから値を返し、スレッド境界を越えて例外を伝播する方法を学びます。
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
// Callableタスクを作成
<Integer> task = new <Integer>() {
public Integer () throws Exception {
return 42;
}
};
// 送信して結果を取得
<Integer> future = executor.__(task);
Integer result = future.();
System.out.println("Result: " + result);
executor.shutdown();
}
}