Java 中的 Callable 和 Future\
java programming java8object oriented programming更新于 2024/10/22 22:53:00
java.util.concurrent。与只能运行线程的 Runnable 接口不同,Callable 对象可以返回线程完成的计算结果。Callable 对象返回 Future 对象,该对象提供用于监视线程正在执行的任务进度的方法。future 对象可用于检查 Callable 的状态,然后在线程完成后从 Callable 中检索结果。它还提供超时功能。
语法
//使用 ThreadExecutor 提交可调用函数 //并以 Future 对象的形式获取结果 Future<Long> result10 = executor.submit(new FactorialService(10)); //使用 Future 对象的 get 方法获取结果 //get 方法等待线程执行,然后返回执行结果。 Long factorial10 = result10.get();
示例
以下 TestThread 程序展示了在基于线程的环境中 Futures 和 Callables 的使用。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class TestThread { public static void main(final String[] arguments) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); System.out.println("Factorial Service called for 10!"); Future<Long> result10 = executor.submit(new FactorialService(10)); System.out.println("Factorial Service called for 20!"); Future<Long> result20 = executor.submit(new FactorialService(20)); Long factorial10 = result10.get(); System.out.println("10! = " + factorial10); Long factorial20 = result20.get(); System.out.println("20! = " + factorial20); executor.shutdown(); } static class FactorialService implements Callable<Long> { private int number; public FactorialService(int number) { this.number = number; } @Override public Long call() throws Exception { return factorial(); } private Long factorial() throws InterruptedException { long result = 1; while (number != 0) { result = number * result; number--; Thread.sleep(100); } return result; } } }
这将产生以下结果。
输出
Factorial Service called for 10! Factorial Service called for 20! 10! = 3628800 20! = 2432902008176640000