我对 RunnableFuture 接口(interface)定义的“正确性”有疑问。这可能是一个关于在java中定义接口(interface)注释的正确争用的问题。
RunnableFuture的run()方法的定义:
Sets this Future to the result of its computation ...
然而,这显然不可能总是正确的,因为 run() 的返回类型是 void
,而 RunnableFuture 只是一个接口(interface),看来如果我们要保证这一点,我们将有了解有关实现类的性质(例如 get() 实现)。
现在,如果 RunnableFuture 实际上返回了一个值,该值被隐藏并且总是由阻塞的 get() 函数返回,这样的定义(由于其实现,它必须出现在类中,而不是接口(interface)中限制),显然是合适的。
因此,我想知道:是否正确定义了此接口(interface)的 run() 方法?
作为反例:Runnable run() 接口(interface)定义总是正确的。
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.
因此,即使 Runnable 未定义任何实现 - 该接口(interface)告诉我们 JVM 如何通过 Runnable 接口(interface)实现线程,而无需在实现类上强加非保证契约。
所以我有3个问题:
RunnableFuture 的文档在某些情况下是否可能不正确?
如果 (1) 是这种情况,是否可以通过 java 约定接受?
RunnableFuture run() 和 Runnable run() 之间的“真正”区别是什么(如果有)?
参见 http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
最佳答案
RunnableFuture
的合约由FutureTask
实现.当您创建一个 FutureTask
时,您提供一个 Callable
或一个 Runnable
和一个值。 FutureTask
的run
方法看起来像这样:
public void run() {
V result;
try {
if(callable) {
result = callable.call();
} else {
runnable.run();
result = value;
}
} catch (Throwable t) {
setException(t);
return;
}
set(result);
}
除了实际实现将 Runnable
值对包装在 Callable
中并进行一些额外检查以确保 FutureTask
是正确的调用 run
之前的状态。
关于java - 可运行的 future 接口(interface)定义(jdk),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12254831/