1. 名词概念
FutureTask:将要发生的任务
2. 应用场景
- 当一个线程需要等待另一个线程把某个任务执行完后它才能继续执行,此时可以使用 FutureTask;
- 当多个线程试图同时执行同一个任务时,只允许一个线程执行任务,其他线程需要等待这个任务执行完后才能继续执行(这是什么场景);
TODO:上述场景待学习完后验证
3. FutureTask内部状态流图
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;
private Callable<V> callable; //执行的任务
private Object outcome; //存储结果或者异常
private volatile Thread runner;//执行callable的线程
private volatile WaitNode waiters; //调用get方法等待获取结果的线程栈
- NEW:表示一个新的任务,初始状态;
- COMPLETING:当任务被设置结果时,处于COMPLETING状态,这是一个中间状态;
- NORMAL:表示任务正常结束;
- EXCEPTIONAL:表示任务因异常而结束;
- CANCELLED:任务还未执行之前就调用了cancel(true)方法,任务处于CANCELLED;
- INTERRUPTING:当任务调用cancel(true)中断程序时,任务处于INTERRUPTING状态,这是一个中间状态;
- INTERRUPTED:任务调用cancel(true)中断程序时会调用interrupt()方法中断线程运行,任务状态由INTERRUPTING转变为INTERRUPTED;
4. 源码分析
(1) 执行任务
FuntureTask#run():
public void run() {
// 如果不是初始状态或者cas设置运行线程是当前线程不成功,直接返回
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 {
// 执行callable任务 这里对异常进行了catch
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex); // 封装异常到outcome
}
if (ran)
set(result);// 将结果赋值给outcome
}
} finally {
runner = null;
int s = state;
// 这里如果是中断中,设置成最终状态
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
FutureTask#set():
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
// 刷新至主存
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
// 唤醒等待线程 waiters
finishCompletion();
}
}
FutureTask#finishCompletion():
private void finishCompletion() {
// assert state > COMPLETING;
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; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null;
(2)获取任务结果
FutureTask#get():
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
// 如果任务完成,则返回;未完成则阻塞线程,等待被唤醒
s = awaitDone(false, 0L);
// 返回任务执行结果outcomme
return report(s);
}
FutureTask#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 (;;) {
//线程可中断,如果当前阻塞获取结果线程执行interrupt()方法,则从队列中移除该节点,并抛出中断异常
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
// 如果已经是最终状态,退出返回
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
// 这里做了个优化,competiting到最终状态时间很短,通过yield比挂起响应更快。
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
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); // 阻塞线程
}
}
4. 实践
(1)一个主线程 + 二个子线程,如何使子线程先执行,再执行主线程(案例并不是子线程,是同步执行)
import java.util.concurrent.*;
public class FutureTaskTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> taskA = new FutureTask<>(() -> "执行任务A");
FutureTask<String> taskB = new FutureTask<>(() -> "执行任务A");
// 异步执行任务A
taskA.run();
// 异步执行任务B
taskB.run();
String respA = taskA.get();
String respB = taskB.get();
System.out.println("执行主线程任务");
}
}
参考资料: