Callable

使用直接继承Thread,或者实现Runnable接口创建线程时,都存在执行完任务后无法获取执行结果的缺陷,Callable和Future应运而生。

@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}

Future

public interface Future<V> {
// 取消任务,取消任务成功返回true,失败则返回false
// 参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务
// 即如果取消已经完成的任务会返回false
// 如果任务还没有执行,返回true
boolean cancel(boolean mayInterruptIfRunning);
// 任务是否被取消成功,如果在任务正常完成前被取消成功,返回true
boolean isCancelled();
// 任务是否已经完成,若完成,返回true
boolean isDone();
// 用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回
V get() throws InterruptedException, ExecutionException;
// 用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}

因为Future只是一个接口,无法直接用来创建对象,所以FutureTask应运而生。

FutureTask

public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}

public class FutureTask<V> implements RunnableFuture<V> {
...
}

所以FutureTask既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

Author: Jiayi Yang
Link: https://jiayiy.github.io/2020/06/14/Callable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.