实例demo
FutureTask task = new FutureTask(new Callable(){
public Object call(){
//....
return new Object();
}
});
task.run();
//这步会阻塞等待
task.get();
问题:为什么线程会在task.get()阻塞等待?
FutureTask 的构造函数
2个构造函数,分别接受Callable和Runnable ,
注意有个int state,在构造的时候设成NEW
public FutureTask<V> implements RunnableFuture<V> {
private volatile int state;
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; //在构造的时候设成NEW
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; //在构造的时候设成NEW
}
}
FutureTask的继承了Runnable 和 Future
public interface RunnableFuture<V> extends Runnable, Future<V>
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
//这里面比较关键就是get方法,也是这个blog的重点
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask里的run()
由上面继承关系可知道FutureTask 继承Runnable ,那么必然会有run方法的实现。
public void run() {
//第一个条件:FutureTask 构造方法里可知道state=NEW ,如果不满足就return
//第二个条件 : 多线程的情况下,cas去争抢runnerOffset,也就是private volatile Thread runner;
//runnerOffset是private volatile Thread runner的一个内存地址,将当前线程设入到runner这个变量里,没抢到的就return了
//这个保证了多线程下FutureTask的线程安全
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方法
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
//如果完成了设置result,并且会更新state 这个字段的状态
if (ran)
set(result);
}
} finally {
...
}
}
protected void set(V v) {
//sate 从NEW变成COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//设置完成结果
outcome = v;
//sate 从COMPLETING变成NORMAL
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
run()方法里都写了注释解释,最后还有个 finishCompletion(),留待后面分析。接下来分析get()方法。
FutureTask里的get()
为什么调用get()会等待就在awaitDone的分析里。
public class FutureTask<V> implements RunnableFuture<V> {
private volatile int state;
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//!!!关键的awaitDone,会阻塞等待
s = awaitDone(false, 0L);
return report(s);
}
//从名字看就是等待完成,这是为什么线程会阻塞的方法
//这是个for(;;) 死循环,这是为什么会阻塞的原因之一不是全部
//线程是不会一直在这里不断的执行,会封装成一个waitnode成为一个等待链表的节点,最后还有个LockSupport.park。等待LockSupport.unPark
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
//如果timed为true,就是等待多长时间还没完成的话就直接返回了
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
//NEW=0 , COMPLETING = 1,NORMAL = 2,EXCEPTIONAL = 3
//CANCELLED = 4,INTERRUPTING = 5,INTERRUPTED = 6
//s > COMPLETING表示完成或其它异常状态可以 return ,这是for循环的跳出点
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) //完成中,线程也没必要那么积极了
Thread.yield();
else if (q == null)
//将线程封装成一个WaitNode,WaitNode是个单链表的节点,多个WaitNode组成了一个等待的链
q = new WaitNode();
else if (!queued)
//调用cas将WaitNode替换到waitersOffset(waiters的内存地址)里,成功替换后 ,WaitNode会在等待链头,并返回queued 为true,表示已经排队成功。
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
// 如果设置timed=true和最长等待时间,超过这个等待时间直接就返回
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
//阻塞,LockSupport.unpark(Thread)会唤醒
LockSupport.park(this);
}
}
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
上面的get()方法会使得线程等待,如果超时就抛出超时异常。什么候线程会唤醒呢?run()里最后还留了个finishCompletion()
private void finishCompletion() {
//waiters就是前面的set里利用cas设入的waitNode
for (WaitNode q; (q = waiters) != null;) {
//先将waiters设成null
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
//遍历单链表,依次去unpark,也就是唤醒线程,直到尾部
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}