java - 可运行的 future 接口(interface)定义(jdk)

标签 java interface runnable future

我对 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个问题:

  1. RunnableFuture 的文档在某些情况下是否可能不正确?

  2. 如果 (1) 是这种情况,是否可以通过 java 约定接受?

  3. RunnableFuture run() 和 Runnable run() 之间的“真正”区别是什么(如果有)?

参见 http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

最佳答案

RunnableFuture的合约由FutureTask实现.当您创建一个 FutureTask 时,您提供一个 Callable 或一个 Runnable 和一个值。 FutureTaskrun 方法看起来像这样:

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/

相关文章:

c# - 如何进行 ASP.NET 依赖注入(inject)

c# - 函数不能返回与返回类型具有相同接口(interface)的类型

android - 在 android 服务的单独线程中运行位置更新

java - 线程等待时出现大量 IllegalMonitorStateException

java - 在 Jtable/ResultSet 中格式化日期

java - Maven 构建失败并显示错误消息 Plugin org.apache.maven.plugins :maven-surefire-plugin:2. 12.4 或其依赖项之一无法解析

java - junit 4 中将一个接口(interface)的多个测试类汇总到一个套件中?

java - Runnable 根本不在 fragment 内运行

Java逐行输出大文件

java - docx4j 3.0 pdf 导出失败并出现 Docx4JException