Callable和future
Callable
Runnable封装了一个异步运行的任务,其run()方法是一个没有参数和值的异步方法
而Callable中的call()方法是带有返回值为模板参数T的异步方法,其源码为
public interface Callable<V> {
V call() throws Exception;
}
Future
Future保存异步计算的结果,可以启动一个计算交给线程,在计算完结果后就可以得到它,其源码为
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
- 若在计算未完成前调用get()将被阻塞
- 若在计算未完成前,调用get(long timeout, TimeUnit unit)且超时将抛出异常
- cancel(boolean mayInterruptIfRunning)可以取消计算,若还没开始则不再开始
RunnableFuture<V>
RunnableFuture<V>又是Future和Runable的子类,其源码为
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
FutureTask
FutureTask包装器可将Callable转为Future和Runable,它是RunnableFuture<V>的子类,如下开启一个计算线程,转为Runnable传入到Thread,再转为Future获取计算的结果
Callable<Integer> myComputation = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 1;
}
};
FutureTask<Integer> task = new FutureTask<>(myComputation);
Thread thread = new Thread(task);
thread.start();
try {
Integer result = task.get();
} catch (Exception e) {
e.printStackTrace();
}