我们都知道线程创建的方式有以下几种
- Thread
- Runnable
- Callable
- Executors
其中Callable是能获取到返回值或者异常的,callable接口如下
@FunctionalInterface
public interface Callable {
/**
* Computes a result, or throws an exception if unable to do so. * * @return computed result
* @throws Exception if unable to compute a result
*/ V call() throws Exception;
}
但callable必须要和线程池搭配使用,或者使用FutureTask,具体用法如下
public interface Future {
//取消任务
boolean cancel(boolean mayInterruptIfRunning);
//是否被取消
boolean isCancelled();
//是否完成,已完成返回true
boolean isDone();
//阻塞获取返回值,如果有异常则抛出异常
V get() throws InterruptedException, ExecutionException;
//指定阻塞时间获取返回值
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
实现类RunnableFuture,该类实现了Runnable接口和Future接口
public interface RunnableFuture extends Runnable, Future {
//将此Future设置为其计算的结果,除非任务取消
void run();
}
实现类FutureTask(重点)
future接口实现一般使用线程池或者FutureTask实现线程调用
//构造方法传入callable赋值给成员变量callable,并设置state为新建
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
state有以下几个状态
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;
FutureTask有下几个成员变量
构造方法1
//构造方法传入的callable对象
private Callable callable;
//线程执行完的返回结果
private Object outcome;
//当前运行的线程
private volatile Thread runner;
//waiters表示如果多个线程执行一个callable对象,则会存在一个单向链表中
private volatile WaitNode waiters;
构造方法2
//带返回值的构造方法
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
由于FutureTask实现了Runnable接口,所以线程调度时执行FutureTask的run方法
public void run() {
//如果状态不为NEW或无法将当前线程设置进去,为runnerOffeset,则返回
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
//如果FutureTask内的Callable不为空且为新建状态,则执行if内部方法
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//执行callale的call方法,且设置ran=true表示执行成功
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
//设置ran=false表示执行失败
ran = false;
//如果捕获到异常,则传入异常
setException(ex);
}
//如果是执行成功,通过set方法设置结果
if (ran)
//将结果设置给set方法
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);
}
}
将callable的返回值通过cas设置进去,并
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
//将状态设置正常NORMAL
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//完成赋值后唤醒UnPack get的线程
finishCompletion();
}
}
如果call方法出现异常,则通过cas设置成功后进行唤醒
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
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;
//唤醒get线程,且将后面所有执行的waitNode节点
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
}
//是否取消,当state>=取消状态,即等于CANCELLED,INTERRUPTING或者INTERRUPTED时返回true
public boolean isCancelled() {
return state >= CANCELLED;
}
//是否完成,当线程不为NEW状态都视为已完成(包括正常完成,异常完成,以及中断等)
public boolean isDone() {
return state != NEW;
}
//阻塞获取返回结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
//当线程小于等于COMPLETING(NEW新建或者COMPLETING准备完成)时,进行无时间闲置的阻塞
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//此处只有当结果返回时上面的阻塞才会被唤醒,否则一直阻塞在上面的if中
return report(s);
}
//阻塞指定时间获取返回结果,当指定时间依旧未获取到结果,抛出TimeoutException异常
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
//传入的时间单位如果为空,则抛空指针异常
throw new NullPointerException();
int s = state;
//当结果未返回且等待时间大于指定的timeout时间,抛出timeout异常
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
//此处只有当结果返回时上面的阻塞才会被唤醒,否则一直阻塞在上面的if中
return report(s);
}
report是根据当前的state判断call方法是执行正常还是失败,正常则返回泛型的result,如果是取消状态,则抛出取消异常,否则抛出ExecutionException异常表示执行异常
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);
}
阻塞方法