表征异步计算的Future:
Future接口有一个get方法,这个方法会执行到计算结束才返回,它可以被中断取消。从它的实现类来看FutureTask来看,其内部也有一个Sync的同步控制类,任务提交的时候会执行
void innerRun() {
if (!compareAndSetState(0, RUNNING))
return;
try {
runner = Thread.currentThread();
if (getState() == RUNNING) // recheck after setting thread
innerSet(callable.call());
else
releaseShared(0); // cancel
} catch (Throwable ex) {
innerSetException(ex);
}
}
调用innerSet的代码:
void innerSet(V v) {
for (;;) {
int s = getState();
if (s == RAN)
return;
if (s == CANCELLED) {
// aggressively release to set runner to null,
// in case we are racing with a cancel request
// that will try to interrupt runner
releaseShared(0);
return;
}
if (compareAndSetState(s, RAN)) {
result = v;
releaseShared(0);
done();
return;
}
}
}
一直循环执行,直到完毕后将状态设置为RAN,同时释放锁。
用户调用Future.get()方法时,会尝试加锁
V innerGet() throws InterruptedException, ExecutionException {
acquireSharedInterruptibly(0);
if (getState() == CANCELLED)
throw new CancellationException();
if (exception != null)
throw new ExecutionException(exception);
return result;
}
任务执行完毕或者被取消时,释放锁,此时返回result。通过这种方式实现异步计算。