标签:tps repo java 异常 表示 执行 响应 als tco
有返回值,可以返回子任务执行的结果.
表示异步计算的结果,可以:
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
解释:
cancel()
: 取消子任务的执行.
mayInterruptIfRunning
判断:
isCancelled()
: 判断任务是否被取消.
cancel()
返回true)idDone()
: 判断任务是否执行结束.(以下情况返回true,否则返回false)
get()
: 获取结果.
CancellationException
异常.ExecutionException
异常.InterruptedException
异常.get(long timeout, TimeUnit unit)
:设定超时限制的get()
,等待超时后,抛出TimeOutException
异常.state
: 用来表示当前任务的运行状态.
outcome
中.outcome
中.cancel(true)
取消异步任务,会调用interrupt()
中断线程的执行.callable
: 封装计算任务,获取计算结果.outcome
: 保存计算任务的返回结果/执行过程中抛出的异常.runner
: 指向当前运行的callable
任务的线程.waiters
: 任务没有结束,调用get()
方法的线程会被阻塞,进入阻塞队列排队等待.状态转移:
cancel(false)
cancel(false)
public void run() {
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 {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
runner = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
流程:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s); // 若正常结束,则返回结果.否则抛出异常
}
流程:
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try {
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally {
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
流程:
子线程返回结果的最后一步 finishCompletion()
private void finishCompletion() {
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
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;
q = next;
}
break;
}
}
done();
callable = null;
}
解释: 在子线程返回结果时,试图唤醒等待队列中的所有阻塞线程.
对于设置阻塞等待时间的线程,若阻塞时间未到但任务已经返回结果,则无需继续等待,直接返回结果.
FutureTask主要采用CAS来替代锁,实现多线程并发.
参考:
标签:tps repo java 异常 表示 执行 响应 als tco
原文地址:https://www.cnblogs.com/truestoriesavici01/p/13216219.html