@FunctionalInterface
public interface Runnable {
public abstract void run();
}
public class MethodReference1 {
public static String ThreadStatus() {
System.out.println( Thread.currentThread().getName() + " is running...");
return "threadname";
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> ThreadStatus());
t1.start();
}
}
在上面使用 Java 8 的示例中,ThreadStatus() 返回一个字符串,但 Runnable 接口(interface)“run()”方法不返回任何值。但它仍然有效(没有编译/运行时错误)。我想知道它是如何工作的,因为根据 lamba 规范,SAM 应该具有完全相同的签名。
如果我翻转 ThreadStatus 方法不返回任何值的情况并将 Functional 接口(interface)方法更改为返回值,我会收到编译时错误。
谁能帮我理解一下?
最佳答案
这是因为 Thread t1 = new Thread(() -> ThreadStatus());
等同于:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
ThreadStatus();
}
});
所以您不会从 run()
返回任何内容。 run()
只是指示调用 ThreadStatus()
方法并忽略返回值。
关于java - 当 SAME 方法在 Java 中不返回值时,Lambda 会返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51914337/