未来任务(当前获取未来即将完成的任务获取返回值)
阅读前,先抱着问题,再来读,效果可能更好
- 为什么还能帮我执行call/run方法的时候,还能拿到返回值?
- 为什么在Future对象get的时候为什么阻塞?
1、继承体系
2、执行原理
3、父类介绍
Future接口
boolean cancel(boolean mayInterruptIfRunning);
//最主要的方法为get()方法获取返回值(阻塞)
V get() ;
V get(long timeout, TimeUnit unit);
boolean isCancelled();
//标识当前任务是否完成,由其他线程变更状态
boolean isDone();
4、属性
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;//已打断
//线程任务
private Callable<V> callable;
//返回值
private Object outcome;
//线程
private volatile Thread runner;
5、构造方法
构造方法
//构造方法之一,直接根据callable的返回值确定返回值
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable 初始态
}
//构造方法之二
//即使构造参数为Runnable,也可以通过适配器的形式进行转换
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
//Executors
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
/**
* A callable that runs given task and returns given result
* 将Runnable封装为Callable对象,
* 且线程的任务在run结束后,直接返回传入的参数result
*/
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() {
task.run();
return result; //传入的参数result
}
}
适配器简单讲解
6、核心方法
V get()
获取返回值
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)//线程状态是否小于COMPLETING(未完成或完成中)
s = awaitDone(false, 0L);//进入等待状态
return report(s);
}
/**
* 等待完成
*/
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;//是否存在超时,由get(long timeout, TimeUnit unit)调用
WaitNode q = null;//进入park的线程用链表的形式,等待队列
boolean queued = false;//是否已入等待队列
for (;;) {
if (Thread.interrupted()) {//响应中断,
removeWaiter(q);//移除结点
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {//如果任务状态>正在完成态,可能异常或取消,返回该状态
if (q != null)
q.thread = null;//由其他线程让其q出队
return s;
}
else if (s == COMPLETING) // cannot time out yet 正在完成中,则出让暂时出让CPU时间片,让其他线程尽快完成。学习到了yield的用法
Thread.yield();
else if (q == null)//建立结点,准备入队
q = new WaitNode();
else if (!queued)//入队
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {//是否超时
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);//wait结点指定时间
}
else
LockSupport.park(this);//wait结点
}
}
链表线程等待队列
入队
remove出队
移除node结点的thread属性为null的结点,从首结点开始,直到最后一个结点。
private void removeWaiter(WaitNode node) {
if (node != null) {
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
if (q.thread != null)//这里不断next的原理就是判断结点的thread是否为null
pred = q;
else if (pred != null) {
pred.next = s;//pred.next=s,s是当前结点的next结点,从这个位置移除结点,只需要干掉上一个结点的next指向即可。
if (pred.thread == null) // check for race 可能有其他线程在竞争上一个结点的出队
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
run()
执行任务,并set结果集
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))//设置runner为当前线程,注意这里调用run方法的线程和调用get的线程不是同一线程。
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {//线程状态为NEW
V result;
boolean ran;
try {
result = c.call();//直接调用call方法而非start
ran = true;//执行成功
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);//set结果集result
}
} finally {//下面的代码不怎么好理解....一般来说run只会由一个线程调用
// 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);
}
}
protected void set(V v) {
//CAS设置状态为COMPLETING,
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;//返回结果集
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state //状态变更为NORMAL
finishCompletion();//唤醒所有的结点,出队,调用钩子函数done()
}
}
小结
FutureTask采用异步的形式set和get返回值,线程在get方法上等待拿到结果集,而执行任务的线程则负责set结果集,有点类似与生产者和消费者。