if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
这个是给结果赋值的方法
调用UNSAFE的cas方法判断本任务状态是NEW 就将状态赋为COMPLETING 一旦赋值成功 就将结果赋为参数v 然后调用UNSAFE的方法将状态改为NORMAL 最后调用finishCompletion方法作后续处理
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
这个是出异常了 给结果赋为异常对象的方法 和上面几乎一样 不多说了
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 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);
}
}
这个是真正运行任务的方法。
首先判断状态不是NEW 或者调用UNSAFE的cas方法将runner设为当前线程的结果为false 如果成立 就直接返回
然后进入try块
然后判断callable是否不为空 且状态是否是NEW 如果成立就设置布尔变量ran 执行call方法 如果不抛出异常就给ran赋为true 抛出了异常就在catch块里 将结果设为空 将ran设为false 将异常给上面的setException方法
最后finally块里 runnr置空 判断如果状态是INTERRUPTING和INTERRUPTED就调用handlePossibleCancellationInterrupts方法强制执行任务线程
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable<V> c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} finally {
// 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
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}
这个方法和上面的方法类似 就是最后返回一个状态 返回的是ran为true且状态是NEW的判断
private void handlePossibleCancellationInterrupt(int s) {
// It is possible for our interrupter to stall before getting a
// chance to interrupt us. Let's spin-wait patiently.
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
}
这个是将任务状态改为可执行的方法