概述
这里Callable 的使用以 FutureTask 举例,源码示例如下
public static void main(String[] args) throws ClassNotFoundException, ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
return 1;
}
});
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
原理
Callable 接口
public interface Callable<V> {
V call() throws Exception;
}
这个接口可以说是平平无奇,就只定义了一个方法
FutureTask
public class FutureTask<V> implements RunnableFuture<V> {...}
public interface RunnableFuture<V> extends Runnable, Future<V> {...}
这里可以发现 FutureTask 也是一个 Runnable,所以一定重写了run()方法
public void run() {
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 = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
这里可以看到这个run()方法,就是执行到了callable 的 call(),返回的结果为 result
最后如果执行成功还会进行 set(result) ,下面就来看看这个方法
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
这里我们看到使用cas 设置outcome 属性为 v ,这个 v 就是前面说的 result,
而outcome 则是FutureTask中的一个Object类型的属性,也就是说,FutureTask 在执行的时候,将结果保存在内部的一个Object属性中
所以,后续才能通过get()获得到这个结果
接下来我们在来看看 futureTask.get() 的get()方法,看看结果是不是如上面猜想的一样
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
//其他的不关注,进入report(s);
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);
}
可以看到当执行futureTask.get() 的时候,获取的就是 outcome,我们上面的猜想完全正确
总结
Callable其实就是将 run 方法里面执行的逻辑抽离出来,而执行的结果通过一个Object类型的属性(outcome)保存
,当我们获取执行结果的时候,并不知得到run()方法的返回值,而是取获取这个 Object 属性(outcome)