一:FutureTask是什么?
创建线程的方式,一般是通过继承Thread或者实现Runnable接口实现,在线程运行结束后如果想获取返回结果,可以使用Handler等实现线程间通讯。而FutureTask可以在运行结束之后直接返回结果。
二:FutureTask结构
三:示例
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// 线程开始
int count = 0;
for (int i = 0; i < 100; i++) {
count += i;
}
Thread.sleep(3000);
// 线程结束,返回结果
return count;
}
});
// 新建线程,执行futureTask
new Thread(futureTask).start();
try {
// 获取返回结果,如果futureTask没有运行结束,则会堵塞当前线程等待
int result = futureTask.get();
Log.i("testLog", "The result is " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
复制代码
源码分析
FutureTask.java
// 状态
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
// 当前运行的线程,用于保证run只执行一次
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
}
// 构造函数,传入的Runnable和返回结果
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
// 是否取消
public boolean isCancelled() {...}
// 是否被执行
public boolean isDone() {...}
// 取消任务
public boolean cancel(boolean mayInterruptIfRunning) {...}
// 获取结果
public V get() {...}
// 获取结果,如果在给定时间内没有执行完成,抛出超时异常
public V get(long timeout, TimeUnit unit) {...}
// 执行
public void run() {...}
复制代码
run()方法
public void run() {
// 1. 状态如果不是NEW,说明任务或者已经执行过,或者已经被取消,直接返回
// 2. 状态如果是NEW,则尝试把当前执行线程保存在runner字段中
// 如果赋值失败则直接返回
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// 执行Callable的call方法,并获取返回结果
result = c.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);
}
}
复制代码
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 {
long startTime = 0L; // Special value 0L means not yet parked
WaitNode q = null;
boolean queued = false;
for (;;) {
int s = state;
// 已完成,异常或者被取消。
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
// 已完成,让出线程优先权
else if (s == COMPLETING)
Thread.yield();
// 线程被打断,移除等待队列,并抛出异常
else if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
// 如果等待队列为空,则创建一个
else if (q == null) {
if (timed && nanos <= 0L)
return s;
q = new WaitNode();
}
// 如果还没有入队列,则把当前节点加入waiters首节点并替换原来waiters
else if (!queued)
queued = U.compareAndSwapObject(this, WAITERS,
q.next = waiters, q);
// 需要等待,则计算等待时间
else if (timed) {
final long parkNanos;
if (startTime == 0L) { // first time
startTime = System.nanoTime();
if (startTime == 0L)
startTime = 1L;
parkNanos = nanos;
} else {
long elapsed = System.nanoTime() - startTime;
if (elapsed >= nanos) {
removeWaiter(q);
return state;
}
parkNanos = nanos - elapsed;
}
if (state < COMPLETING)
LockSupport.parkNanos(this, parkNanos);
}
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);
}
复制代码
任务取消
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
U.compareAndSwapInt(this, STATE, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try {
// 打断线程
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
// interrupt()方法只是设置中断标志位
//如果被中断的线程处于sleep()、wait()或者join()逻辑中则会抛出InterruptedException异常。
t.interrupt();
} finally { // final state
U.putOrderedInt(this, STATE, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
// 唤醒所有等待线程,移除所有等待队列
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (U.compareAndSwapObject(this, WAITERS, 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
}
复制代码
五:小结
- FutureTask是可以被线程执行并获取返回执行结果的。
- 其他线程在获取FutureTask的执行结果时,如果FutureTask未执行结束,则会被堵塞等待的。
- FutureTask调用cancel(true)并不一定能停止当前的线程。
参考: