gpt4 book ai didi

java - 如果您在 Thread 构造函数中传递无参数并且不扩展 Thread 类怎么办?

转载 作者:行者123 更新时间:2023-11-30 06:13:44 25 4
gpt4 key购买 nike

如果我这样做,后台会发生什么:

class TestThread {
public static void main(String[] args) {
Thread t = new Thread();
t.start();

System.out.println(t.getName());
}
}

我知道要创建一个新线程,您必须通过扩展 Thread 类或实现 Runnable 来覆盖 run() 方法> 界面。

如果我们实现Runnable接口(interface),我们必须提供目标运行方法,其中提供必须并发运行的代码。

此外,如果我们不重写 run() 方法,也不扩展 Thread 或实现 Runnable,则 >main() 线程将执行。

我想知道当我执行上面的代码时,后台到底会发生什么? main 是否有像其他 Thread 一样的 run() 方法?除了main线程之外,这还会创建一个新的Thread吗?

最佳答案

/**
* 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 Threads?

低级 API 可用于此目的。他们不一定需要创建 Thread 实例来运行线程。这是一个很好的讨论:How main thread created by Java?

关于java - 如果您在 Thread 构造函数中传递无参数并且不扩展 Thread 类怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49679211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com