使用
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new Callable() {
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
return 20;
}
});
new Thread(futureTask).start();
System.out.println(System.currentTimeMillis());
Integer o = (Integer) futureTask.get();
System.out.println(o);
System.out.println(System.currentTimeMillis());
}
Callable/Future 可以阻塞线程,获取线程的返回值
源码分析
继承关系
public interface Runnable {
public abstract void run();
}
public interface Future<V> {
//取消
boolean cancel(boolean mayInterruptIfRunning);
//是否取消
boolean isCancelled();
//是否执行结束
boolean isDone();
//获得返回值
V get() throws InterruptedException, ExecutionException;
//获得返回值 带超时时间
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V> {
//状态 下面的值
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; // non-volatile, protected by state reads/writes
//执行线程
private volatile Thread runner;
private volatile WaitNode waiters;
//构造方法
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
//线程启动时执行的方法
public void run() {
//如果当前状态不是NEW 或者 设置线程失败,说明有其他线程在执行任务
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 {
result = c.call();//执行call方法,例子中重写的call方法
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)//正常执行完成,设值
set(result);
}
} finally {
runner = null;//清理数据
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//设值方法
protected void set(V v) {
//设置状态为 COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;//将返回值设置给成员变量
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // 将状态设置为NORMAL
finishCompletion();
}
}
//处理
private void finishCompletion() {
// 循环清理所有数据
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
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
//get方法
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)//未执行完成,挂起
s = awaitDone(false, 0L);
return report(s);//返回值方法
}
//挂起
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 还未执行完成,让出时间,等待执行完成
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//初始状态,初始化新的 WaitNode
else if (q == null)
q = new WaitNode();
else if (!queued)//将q设置到队列中
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 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);
}
}