Future<?> 的可运行实例?
Runnable instanceof Future<?>?
我正在阅读一些 javadoc 并且遇到了 this example from ThreadPoolExecutor.afterExecute(...)
javadocs:
class ExtendedExecutor extends ThreadPoolExecutor {
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
System.out.println(t);
}
}
任何人都可以解释一下代码如何通过第一个 if。我的意思是 r
如何成为 instanceof Future<?>
?
Can anybody explain me how the code can pass the first if. I mean how r can be instanceof Future?
你的困惑是对的。传入 Runnable
然后尝试将其转换为不扩展 Runnable
的 Future
是有点奇怪的代码。这不是您经常看到的模式。这在 ThreadPoolExecutor.afterExecute(...)
javadocs 的 javadoc 中,在查看代码后,该方法的 r
参数是已完成的任务。
我认为如果它是 FutureTask
而不是 Future
,代码会更干净。 FutureTask
甚至在 javadocs 中的示例代码上方提到:
When actions are enclosed in tasks (such as {@link FutureTask})...
FutureTask
实现了 RunnableFuture
,它既是 Runnable
又是 Future
,所以代码可以工作,但使用 FutureTask
会更容易混淆。
'?'是类型参数,不是类型参数!
我正在阅读一些 javadoc 并且遇到了 this example from ThreadPoolExecutor.afterExecute(...)
javadocs:
class ExtendedExecutor extends ThreadPoolExecutor {
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
System.out.println(t);
}
}
任何人都可以解释一下代码如何通过第一个 if。我的意思是 r
如何成为 instanceof Future<?>
?
Can anybody explain me how the code can pass the first if. I mean how r can be instanceof Future?
你的困惑是对的。传入 Runnable
然后尝试将其转换为不扩展 Runnable
的 Future
是有点奇怪的代码。这不是您经常看到的模式。这在 ThreadPoolExecutor.afterExecute(...)
javadocs 的 javadoc 中,在查看代码后,该方法的 r
参数是已完成的任务。
我认为如果它是 FutureTask
而不是 Future
,代码会更干净。 FutureTask
甚至在 javadocs 中的示例代码上方提到:
When actions are enclosed in tasks (such as {@link FutureTask})...
FutureTask
实现了 RunnableFuture
,它既是 Runnable
又是 Future
,所以代码可以工作,但使用 FutureTask
会更容易混淆。
'?'是类型参数,不是类型参数!