成员变量和常量
/**
* The run state of this task, initially NEW. The run state
* transitions to a terminal state only in methods set,
* setException, and cancel. During completion, state may take on
* transient values of COMPLETING (while outcome is being set) or
* INTERRUPTING (only while interrupting the runner to satisfy a
* cancel(true)). Transitions from these intermediate to final
* states use cheaper ordered/lazy writes because values are unique
* and cannot be further modified.
*
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
//用来表示当前任务的状态,直接看上面注释就ok了
private volatile int state;
private static final int NEW = 0; //初始状态
private static final int COMPLETING = 1; //运行中
private static final int NORMAL = 2; //运行完毕
private static final int EXCEPTIONAL = 3; //运行过程中发生了异常
private static final int CANCELLED = 4; //被取消了
private static final int INTERRUPTING = 5; //终止过程中的中间状态
private static final int INTERRUPTED = 6; //终止了
/** The underlying callable; nulled out after running */
//业务逻辑
private Callable<V> callable;
/** The result to return or exception to throw from get() */
//任务执行结果 , 可以是异常
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
//在运行的线程
private volatile Thread runner;
/** Treiber stack of waiting threads */
//在等待获取结果的线程节点
private volatile WaitNode waiters;
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
//CAS操作state runner waiters 成员变量
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
构造函数
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
//初始状态为NEW
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
//将runnable包装为callable , 返回值为入参的result
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
实现了RunnableFuture接口。先看到Runnable的run方法。
public void run() {
//状态不为NEW 或者 cas设置runner为当前线程失败(多个线程来竞争运行该任务,只需要其中一个线程抢到就可以了) 。 则直接返回
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
//任务不能空,状态要为NEW,才能运行
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//调用call方法执行业务代码
result = c.call();
//将ran修改为true
ran = true;
} catch (Throwable ex) {
//call方法发生异常
result = null;
//ran修改为false
ran = false;
//设置异常给返回结果,并设置任务状态
setException(ex);
}
//没有发生异常,则设置result给返回结果,并设置任务状态
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
//任务执行完毕,runner置空,
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
//如果任务被终止
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
call方法运行异常
protected void setException(Throwable t) {
//cas将任务状态从NEW修改为COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//将返回结果设置为异常对象
outcome = t;
//cas将任务状态修改为EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
//唤醒等待的线程获取任务执行的结果
finishCompletion();
}
}
call方法正常运行
protected void set(V v) {
//cas将任务状态从NEW修改为COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//设置返回结果
outcome = v;
//cas将任务状态修改为NORMAL
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//唤醒等待的线程获取任务执行的结果
finishCompletion();
}
}
finishCompletion方法
private void finishCompletion() {
// assert state > COMPLETING;
//如果有节点在等待
for (WaitNode q; (q = waiters) != null;) {
//cas将waitres设置为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;
//存在下一个等待节点,next引用断开
q.next = null; // unlink to help gc
//获取下一个等待节点
q = next;
}
//跳出循环
break;
}
}
//供子类实现的空方法
done();
callable = null; // to reduce footprint
}
handlePossibleCancellationInterrupt
private void handlePossibleCancellationInterrupt(int s) {
//任务状态为 终止中
if (s == INTERRUPTING)
//直到任务状态被设置为INTERRUPTED , 一直让出cpu
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
}
接着看到实现了Future接口的相关方法
public boolean cancel(boolean mayInterruptIfRunning) {
//mayInterruptIfRunning 来决定任务状态为INTERRUPTING 还是 CANCELLED
//任务状态为NEW 且 cas将状态由NEW修改为 INTERRUPTING或CANCELLED
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
//上述操作执行失败,则取消任务失败
return false;
try {
//如果mayInterruptIfRunning为true
if (mayInterruptIfRunning) {
try {
Thread t = runner;
//runner不为空,说明任务还没结束
if (t != null)
//则调用interrupt方法进行打断
t.interrupt();
} finally { // final state
//打断方法调用完毕,将任务状态设置为INTERRUPTED
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
//状态为 取消和终止
public boolean isCancelled() {
return state >= CANCELLED;
}
//任务状态不是NEW。
public boolean isDone() {
return state != NEW;
}
//获取任务执行的结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
//任务未执行完毕
if (s <= COMPLETING)
//等待任务执行完毕
s = awaitDone(false, 0L);
//返回结果
return report(s);
}
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
//任务未执行完毕,且过了指定时间后,仍然未完成,抛出超时异常
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
report方法
private V report(int s) throws ExecutionException {
//获取执行结果
Object x = outcome;
//任务正常执行完毕直接返回
if (s == NORMAL)
return (V)x;
//任务被取消或者终止
if (s >= CANCELLED)
throw new CancellationException();
//任务执行发生了异常
throw new ExecutionException((Throwable)x);
}
awaitDone方法,线程等待任务执行完毕获取结果
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
//是否指定了超时
//计算最终的超时时间
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;
//如果任务 已经执行完毕 或者被取消 或者被终止
if (s > COMPLETING) {
//如果当前线程已经是等待节点了
//将等待节点的线程设置为空
if (q != null)
q.thread = null;
//返回任务的执行状态
return s;
}
//如果任务状态刚好是COMPLETING,此时任务执行结果还没来得及设置给outcome变量,则让出cpu
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//任务还未执行完毕
//将当前线程包装为WaitNode对象 , 当前线程此时并不休眠,接着下一个循环
else if (q == null)
q = new WaitNode();
//任务还未执行完毕,且当前线程已经是等待节点了
//cas将waiters设置为,当前线程的等待节点,并将当前线程的等待节点的下一个节点设置为waiters
//cas成功,则queued被修改为true
//当前线程此时仍然不休眠,接着下一个循环
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
//如果设置了超时等待
else if (timed) {
//剩余的等待时间
nanos = deadline - System.nanoTime();
//超时了
if (nanos <= 0L) {
//移除相应的等待节点
removeWaiter(q);
return state;
}
//没有超时,接着休眠剩余时间
LockSupport.parkNanos(this, nanos);
}
//没有设置超时等待,休眠
else
LockSupport.park(this);
}
}
removeWaiter方法
private void removeWaiter(WaitNode node) {
if (node != null) {
//先将node的thread属性设置为空
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
//获取waiters为q,开始循环遍历
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
//获取到q的下一个节点为s
s = q.next;
//如果thread不为空,则将pred 设置为q
if (q.thread != null)
pred = q;
//如果pred不为空
else if (pred != null) {
//pred记录了thread不为空的上一个节点
//将pred的下一个节点设置为s , 则跳过了中间thread为空的节点
pred.next = s;
//再次检查pred的thread属性是否为空(任务执行完毕,任务被终止,被取消,都会将thread设置为空,则此时检查,可以及时删除无用节点)
//如果为空,则重新外层的循环
if (pred.thread == null) // check for race
continue retry;
}
//当前节点q的thread属性为空,且pred为空,则cas将waiters从q设置为s(q的下一个节点)
//设置失败,则重新外层的循环
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
//内层for循环执行完毕,跳出外层死循环
break;
}
}
}
WaitNode对象
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}