FutureTask源码分析
FutureTask<V>实现了RunnableFuture<V>接口。内部变量包含Sync类型的变量sync。
public V get() throws InterruptedException, ExecutionException {
return sync.innerGet();
}
为对应的获取任务执行结果的方法。
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return sync.innerGet(unit.toNanos(timeout));
}
为对应的加入时限的获取任务执行结果的方法。
sync内部的带有时间限制的get方法为:
- //获取结果
- V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {
- //调用AbstractQueuedSynchronizer里的方法
- // return tryAcquireShared(arg) >= 0 ||doAcquireSharedNanos(arg, nanosTimeout);
- // 首先tryAcquireShared调用它获取锁,也就是看任务完事没,如果任务完事了就返回TRUE,那么执行逻辑同上。
- // 如果获取不到锁,那么就阻塞当前线程给定的时间,如果时间到了再次任务还没完成则抛出异常。
- if (!tryAcquireSharedNanos(0, nanosTimeout))
- throw new TimeoutException();
- if (getState() == CANCELLED)
- throw new CancellationException();
- if (exception != null)
- throw new ExecutionException(exception);
- return result;
- }
内部任务执行对应的操作为:
void innerRun() {
//如果任务不是初始状态则直接结束
if (!compareAndSetState(READY, RUNNING))
return;
runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
result = callable.call();
} catch (Throwable ex) {
//我们写的任务方法里如果出现异常则调用setException
setException(ex);
return;
}
//设置结果
set(result);
} else {
//释放锁
releaseShared(0); // cancel
}
}