0
下面是从书中Java并发实践的片段,我感到困惑:为什么我们可以将FutureTask <V>对象分配给Future <V>变量?
interface Computable<A, V> {
V compute(A arg) throws InterruptedException;
}
public class Memoizer3<A, V> implements Computable<A, V> {
private final Map<A, Future<V>> cache
= new ConcurrentHashMap<A, Future<V>>();
private final Computable<A, V> c;
public Memoizer3(Computable<A, V> c) { this.c = c; }
public V compute(final A arg) throws InterruptedException {
Future<V> f = cache.get(arg);
if(f == null) {
Callable<V> eval = new Callable<V>() {
@Override
public V call() throws Exception {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
//How could it happen???
f = ft;
cache.put(arg, ft);
ft.run();
}
try {
return f.get();
} catch (InterruptedException e) {
throw launderThrowable(e.getCause());
}
}
}
正如代码显示的,˚F类型为未来而英尺的类型是FutureTask。为什么我们可以将ft分配给变量f?
FutureTask是Future接口的基础具体实现,并提供异步处理。 –