为什么允许使用 NON Runnable 参数创建 Thread 实例?
Why it is allowable to create Thread instance with NON Runnable argument?
我在文章中遇到了这样的代码(我稍微简化了一下):
public class Main {
static class A {
}
public static void main(String[] args) {
new Thread(A::new).start();
}
}
我对该代码感到惊讶,因为从我的角度来看,如果它必须产生编译时错误,因为 Thread
构造函数接受 Runnable
但 A
没有方法 run
但它编译甚至启动时没有任何 errors/exceptions。我在我的 PC 上检查了它的几种变体,但它仍然有效。
所以我有以下问题:
为什么没有编译错误?
执行哪个方法而不是 运行 方法?
A Runnable
is a FunctionalInterface
也可以像您的情况一样用 lambda 表达式表示:
new Thread(() -> new A())
这只不过是方法引用的类似表示
A::new
在您的代码中相当于
new Runnable() {
@Override
public void run() {
new A(); // just creating an instance of 'A' for every call to 'run'
}
}
我在文章中遇到了这样的代码(我稍微简化了一下):
public class Main {
static class A {
}
public static void main(String[] args) {
new Thread(A::new).start();
}
}
我对该代码感到惊讶,因为从我的角度来看,如果它必须产生编译时错误,因为 Thread
构造函数接受 Runnable
但 A
没有方法 run
但它编译甚至启动时没有任何 errors/exceptions。我在我的 PC 上检查了它的几种变体,但它仍然有效。
所以我有以下问题:
为什么没有编译错误?
执行哪个方法而不是 运行 方法?
A Runnable
is a FunctionalInterface
也可以像您的情况一样用 lambda 表达式表示:
new Thread(() -> new A())
这只不过是方法引用的类似表示
A::new
在您的代码中相当于
new Runnable() {
@Override
public void run() {
new A(); // just creating an instance of 'A' for every call to 'run'
}
}