Callable接口
//Runnable是没有返回结果的任务,而Callable则是有返回结果的任务
public interface Callable<V> {
/**
* 有返回结果,并且可能抛出异常
*/
V call() throws Exception;
}
Future接口
package java.util.concurrent;
/**
* 表示异步执行的结果,有三个功能:
* 1.获取异步执行任务的结果
* 2.查看异步任务的执行状态(取消或终止)
* 3.取消异步任务
*/
public interface Future<V> {
/**
* 尝试取消任务,如果任务已经完成或已经取消,则取消失败。
* 1.如果任务没未被启动,则该任务不会被运行;
* 2.如果任务已经被启动,参数mayInterruptIfRunning决定是否执行当前任务
* 的线程是否应该被中断,这只是作为一种终止任务的尝试。
* 执行这个方法之后,以后的isDone方法调用都会返回true。
* 如果这个方法返回true,以后的isCancelled方法调用都会返回true。
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* cancel()调用返回true之后,这个方法会返回true。
*/
boolean isCancelled();
/**
* 如果当前任务执行成功,或者被取消,或者抛出异常,则返回true
*/
boolean isDone();
/**
* 阻塞直到任务完成,并返回任务执行结果。
* 当异步任务被取消,或抛出异常,get()方法会抛出相应的异常
*/
V get() throws InterruptedException, ExecutionException;
/**
* 阻塞一定时间等待任务完成,并返回任务执行结果,超过时间未返回结果会抛出异常
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask
总结:
1.状态为NEW时,cancel和run方法才可以被运行
2.run方法对cancel方法的影响
在调用call()方法期间,cancel()方法还可以运行;
如果call()方法返回或抛出异常之后CAS成功,则cancel()方法之后都会返回false
意义:
在任务还未开始,或者任务已被运行,但未结束,这两种情况下都可以取消;
如果任务已经结束,则不可以被取消
3.cancel方法对run方法的影响
cancel()方法第一步CAS成功之后,
1)如果run()方法还没运行,之后就不可以再被运行;
2)如果run()方法已经调用call()方法,则call()方法可以运行直至返回或抛出异常,但run()方法的第二步中的CAS会失败,且运行结果也不会被设置
意义:
取消成功后,如果任务还未开始,则之后也不会得到运行;
如果任务已经开始,则可以运行直至返回或抛出异常,但任务结果或异常不会被设置
/**
* Run方法执行成功会把Future置为完成状态,并且Future可以获取Run方法的执行结果
*/
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
/**
* FutureTask表示可以取消的异步任务
* 从继承关系可以看出,FutureTask至少包含以下四个内容:
* 1.任务内容——run()方法
* 2.获取任务结果——get()方法
* 3.获取任务状态——isCancelled()和isDone()方法
* 4.取消任务——cancel()方法
*/
public class FutureTask<V> implements RunnableFuture<V> {
/**
* 当前任务的运行状态。
*
* 可能存在的状态转换
* NEW -> COMPLETING -> NORMAL(有正常结果)
* NEW -> COMPLETING -> EXCEPTIONAL(结果为异常)
* NEW -> CANCELLED(无结果)
* NEW -> INTERRUPTING -> INTERRUPTED(无结果)
*/
private volatile int state;
private static final int NEW = 0;//初始状态
private static final int COMPLETING = 1;//
private static final int NORMAL = 2;//任务正常完成,结果被set
private static final int EXCEPTIONAL = 3;//任务抛出异常
private static final int CANCELLED = 4;//任务已被取消
private static final int INTERRUPTING = 5;//线程中断状态被设置ture,但线程未响应中断
private static final int INTERRUPTED = 6;//线程已被中断
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** 用于get()返回的结果,也可能是用于get()方法抛出的异常 */
private Object outcome; // non-volatile, protected by state reads/writes
/** 执行callable的线程,调用FutureTask.run()方法通过CAS设置 */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
//构造函数1,赋值callable,并初始化状态为NEW
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
//构造函数2,赋值callable,并初始化状态为NEW
public FutureTask(Runnable runnable, V result) {
//返回的callable的call方法会调用runnable.run方法,然后返回result
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public boolean isCancelled() {
return state >= CANCELLED;
}
/**
* 由isCancelled和isDone两个方法可以看出
* 1.完成状态包括:任务正常完成、异常、取消
* 2.取消状态包括:已被取消,已被中断,中断中
*/
public boolean isDone() {
return state != NEW;
}
/**
* cancel方法
* 1.根据mayInterruptIfRunning是否为true,CAS设置状态为INTERRUPTING或CANCELLED,
* 设置成功,继续第二步,否则返回false
* 2.如果mayInterruptIfRunning为true,调用runner.interupt(),设置状态为INTERRUPTED
* 3.唤醒所有在get()方法等待的线程
*/
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
/**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
/**
* @throws CancellationException {@inheritDoc}
*/
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);
}
@SuppressWarnings("unchecked")
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);
}
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;
}
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);
}
}
private void removeWaiter(WaitNode node) {
if (node != null) {
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
if (q.thread != null)
pred = q;
else if (pred != null) {
pred.next = s;
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
/**
* 1.设置运行线程runner为当前线程,保证任务在同一时刻只被一个线程执行
* 2.调用callable.call()方法,两种结果:
* 1)运行成功:CAS状态为COMPLETING,如果成功,设置result为call()的返回值,
* 设置状态为NORMAL,唤醒所有在get()方法上等待的线程
* 2)运行抛出异常:CAS状态为COMPLETING,如果成功,设置result为call()的异常,
* 设置状态为EXCEPTIONAL,唤醒所有在get()方法上等待的线程
* 3.如果当前状态为INTERRUPTING(步骤2已CAS失败),则一直调用Thread.yield()直至状态不为INTERRUPTING
*/
public void run() {
//保证任务在同一时刻只被一个线程执行,同时设置运行线程runner为当前线程
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);
}
}
//设置最终状态为NORMAL,并唤醒所有调用get()方法的等待线程
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
//设置最终状态为EXCEPTIONAL,并唤醒所有调用get()方法的等待线程
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
//唤醒所有在get()方法上等待的线程,设置callable = null,调用回调方法done()
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; // to reduce footprint
}
//钩子方法,默认无实现,用于在任务done的时候执行某些回调事件
protected void done() { }
//当状态为INTERRUPTING,一直调用yield?
private void handlePossibleCancellationInterrupt(int s) {
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
}
//Treiber栈,用于记录等待线程
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
// 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;
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);
}
}
}