java - Java中主线程什么时候停止?

标签 java multithreading jvm

我读到了这个声明:

The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.

这是真的吗?

我也知道了“即使主线程死了,程序仍然运行”。

这是我目前的理解:

  • 当您启动一个程序时,JVM 会创建一个线程来运行您的程序。
  • JVM 创建一个用户线程来运行程序。该线程称为主线程。
  • 从主线程调用该类的 main 方法。
  • 如果程序从主线程生成新线程,则程序会等待,直到最后一个线程终止。

哪一个是正确的?

最佳答案

当所有非守护线程死亡时,程序终止(守护线程是用 setDaemon(true) 标记的线程;它通常用于实用程序线程)。来自 documentation :

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

关于java - Java中主线程什么时候停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898765/

相关文章:

java - 如何解决 WebLogic 服务器 BEA-000117 和 BEA-101162 错误?

java - 显示来自数据的图像

c# - 加速控制台应用程序,并发?并行编程?

c++ - 使用多线程迭代未排序的数据结构(如数组、树)可以使迭代更快吗?

linux - 如何确保信号处理程序永远不会屈服于同一进程组中的线程?

java - 通过java程序读取JVM堆bin文件

java - 从邮件中下载附件并使用java保存

java - 如何在测试中调用设置方法来停止重写相同的代码

java - 将资源添加到现有 Maven 项目中

java - 在多处理器系统中,每个处理器都会有独立的JVM吗?