一、回顾Runnable和Callable
区别:
- Callable定义了call()方法,Runnale定义了run()方法。
- call()方法可以抛出异常,run()方法无法抛出异常。
- Callable有返回值,是泛型的,创建的时候传递进去,执行结束后返回。
- Callable执行任务的时候可以通过FutureTask得到任务执行的状态。
联系:
- Callable的call方法实际执行在Runnable的run方法中。
- Runnable实例对象需要Thread包装启动,Callable先通过FutureTask(本质还是Runnable)包装,再给Thread包装执行。
二、Future机制原理
Future就是对于具体的Runnable或Callable任务的执行结果进行取消,查询是否完成,获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
JDK内置的Future主要使用了Callable接口和FutureTask类。下面对源码进行解析:
Callable接口:
@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;
}
如何使用Callable:
一般情况下都是配合ExecutorService来使用的,在ExecutorService接口中声明了三个submit方法,用来生成Future对象,参数为Callable实例或Runnable实例。
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
继承关系:
public class FutureTask<V> implements RunnableFuture<V> {}
public interface RunnableFuture<V> extends Runnable, Future<V> { void run();}
关系明确: FutureTask类实现了RunnableFuture接口,RunnableFuture接口又继承了Runnable接口和Future接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,拥有Future接口提供的各种方法。
流程跑通: 通常把任务定义Callable接口的call方法内部,返回值为泛型,再生成一个FutureTask的对象,FutureTask构造方法内部参数封装着Callable实例,然后把这个对象当作一个Runnable,作为参数传递给Thread包装执行。
三、Future源码解析
Future接口提供的方法:
public interface Future<V> {
//取消任务。参数:是否立即中断任务执行,或者等等任务结束
boolean cancel(boolean mayInterruptIfRunning);
//任务是否已经取消,若已取消,返回true
boolean isCancelled();
//任务是否已经完成。包括任务正常完成、抛出异常或被取消,都返回true
boolean isDone();
/*会一直阻塞等待任务执行结束,获得V类型的结果。InterruptedException: 线程被中断异常, ExecutionException: 任务执行异常,如果任务被取消,还会抛出CancellationException*/
V get() throws InterruptedException, ExecutionException;
/*参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask源码解析:
构造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
//状态为NEW
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
实际上,Callable = Runnable + result,看Executors.callable(runnable,result)的实现:
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
//new了一个RunnableAdapter,返回Callable,说明RunnableAdapter实现了Callable
return new RunnableAdapter<T>(task, result);
}
利用RunnableAdapter适配器实现了将Runnable转为Callable,继续看RunnableAdapter类:
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
//Runnable task执行了run()
task.run();
//返回了T result
return result;
}
}
本质上还是Runnable去执行run方法,只是增加了result常量来接受返回的结果而已。
状态值:
/* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
private volatile int state;
//初始化状态
private static final int NEW = 0;
//正在执行
private static final int COMPLETING = 1;
//正常完成
private static final int NORMAL = 2;
//出现异常
private static final int EXCEPTIONAL = 3;
//被取消
private static final int CANCELLED = 4;
//正被中断
private static final int INTERRUPTING = 5;
//已被中断
private static final int INTERRUPTED = 6;
FutureTask的run方法:
public void run() {
/*compareAndSwapObject(this, runnerOffset,]null, Thread.currentThread()))
其中第一个参数为需要改变的对象,第二个为偏移量,第三个参数为期待的值,第四个为更新后的值。
*/
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//call()方法是由FutureTask调用的,说明call()不是异步执行的
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//设置异常
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
//判断是否被中断
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
set方法:
protected void set(V v) {
// NEW -> COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//返回结果,也包括异常
outcome = v;
//COMPLETING -> NORMAL
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//唤醒等待的线程
finishCompletion();
}
}
将返回值和状态赋值回去。
get方法:
public V get() throws InterruptedException, ExecutionException {
int s = state;
//是否是未完成状态,是则等待
if (s <= COMPLETING)
//等待过程
s = awaitDone(false, 0L);
return report(s);
}
/**
* @throws CancellationException {@inheritDoc}
*/
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
run方法解析完成,使用get方法获取返回结果。
总结:Future只实现了异步,而没有实现回调,主线程get时会阻塞,可以轮询以便获取异步调用是否完成。但Guava ListenableFuture实现异步非阻塞,目的就是多任务异步执行,通过回调的方方式来获取执行结果而不需轮询任务状态,说白了就是设置监听器,任务执行结束自动回调返回结果,不用一直阻塞在等待结果中。
来源:CSDN
作者:小白写程序
链接:https://blog.csdn.net/qq_41030039/article/details/103933666