可赎回和未来
虽然 Runnable 提供了一种将代码包装在不同线程中的方法,但它有一个限制,即它不能从执行中返回结果。从执行 Runnable 获得一些返回值的唯一方法是将结果分配给在 Runnable 之外的范围内可访问的变量。
Callable 作为 Runnable 的同行在 Java 5 中引入。Callable 基本上是相同的,除了它有 call 方法而不是 run。call 方法具有返回结果的附加功能,并且还允许抛出已检查的异常。
可调用任务提交的结果*可*通过 Future 进行挖掘 ******
Future 可以被认为是包含 Callable 计算结果的各种容器。可调用的计算可以在另一个线程中继续进行,任何尝试点击 Future 的结果都将被阻止,并且只有在结果可用时才返回结果。
可调用接口
public interface Callable<V> {
    V call() throws Exception;
}
未来
interface Future<V> {
    V get();
    V get(long timeout, TimeUnit unit);
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
}
使用 Callable 和 Future 示例:
public static void main(String[] args) throws Exception {
    ExecutorService es = Executors.newSingleThreadExecutor();
          
    System.out.println("Time At Task Submission : " + new Date());
    Future<String> result = es.submit(new ComplexCalculator());
    // the call to Future.get() blocks until the result is available.So we are in for about a 10 sec wait now
    System.out.println("Result of Complex Calculation is : " + result.get());
    System.out.println("Time At the Point of Printing the Result : " + new Date());
}
我们的 Callable 执行冗长的计算
public class ComplexCalculator implements Callable<String> {
    @Override
    public String call() throws Exception {
        // just sleep for 10 secs to simulate a lengthy computation
        Thread.sleep(10000);            
        System.out.println("Result after a lengthy 10sec calculation");
        return "Complex Result"; // the result 
    }
}
输出
Time At Task Submission : Thu Aug 04 15:05:15 EDT 2016
Result after a lengthy 10sec calculation
Result of Complex Calculation is : Complex Result
Time At the Point of Printing the Result : Thu Aug 04 15:05:25 EDT 2016
Future 上允许的其他操作
虽然 get() 是提取实际结果的方法,但 Future 已提供
- get(long timeout, TimeUnit unit)定义当前线程等待结果的最大时间段;
- 要取消任务,请拨打 cancel(mayInterruptIfRunning)。标志mayInterrupt表示如果任务已启动并且正在运行,则应该中断该任务;
- 通过调用 isDone()来检查任务是否完成/完成;
- 检查冗长的任务是否被取消了。