如果您在 Thread 构造函数中传递无参数并且不扩展 Thread class 怎么办?
What if you pass a no-arg in the Thread constructor and don't extend the Thread class?
如果我这样做,后台会发生什么:
class TestThread {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
System.out.println(t.getName());
}
}
我知道要创建一个新线程,您必须通过扩展 Thread
class 或实现 Runnable
接口来覆盖 run()
方法。
如果我们实现 Runnable
接口,我们必须提供目标 运行 方法,其中提供必须同时 运行 的代码。
此外,如果我们不覆盖run()
方法并且不扩展Thread
或实现Runnable
,main()
线程将执行。
我想知道当我执行上面的代码时,后台到底会发生什么? main 是否像其他 Thread
一样有一个 run()
方法?这会在 main
线程之外创建一个新的 Thread
吗?
新线程创建、启动、执行空*方法并终止。
*) 不是真的空:
public void run() {
if (target != null) {
target.run();
}
}
/**
* If this thread was constructed using a separate
* Runnable run object, then that
* Runnable object's run method is called;
* otherwise, this method does nothing and returns.
*
* Subclasses of Thread should override this method.
*/
public void run() {
if (target != null) {
target.run();
}
}
由于您尚未设置 Runnable
目标,因此不会发生任何事情。
Does the main have a run()
method like other Thread
s?
Low-level API 可用于此目的。他们不一定需要为 运行 线程创建 Thread
实例。这是一个很好的讨论:How main thread created by Java?
如果我这样做,后台会发生什么:
class TestThread {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
System.out.println(t.getName());
}
}
我知道要创建一个新线程,您必须通过扩展 Thread
class 或实现 Runnable
接口来覆盖 run()
方法。
如果我们实现 Runnable
接口,我们必须提供目标 运行 方法,其中提供必须同时 运行 的代码。
此外,如果我们不覆盖run()
方法并且不扩展Thread
或实现Runnable
,main()
线程将执行。
我想知道当我执行上面的代码时,后台到底会发生什么? main 是否像其他 Thread
一样有一个 run()
方法?这会在 main
线程之外创建一个新的 Thread
吗?
新线程创建、启动、执行空*方法并终止。
*) 不是真的空:
public void run() {
if (target != null) {
target.run();
}
}
/**
* If this thread was constructed using a separate
* Runnable run object, then that
* Runnable object's run method is called;
* otherwise, this method does nothing and returns.
*
* Subclasses of Thread should override this method.
*/
public void run() {
if (target != null) {
target.run();
}
}
由于您尚未设置 Runnable
目标,因此不会发生任何事情。
Does the main have a
run()
method like otherThread
s?
Low-level API 可用于此目的。他们不一定需要为 运行 线程创建 Thread
实例。这是一个很好的讨论:How main thread created by Java?