Java应用程序生命周期

发布于 2024-10-09 11:42:41 字数 154 浏览 2 评论 0原文

典型的 Java 应用程序何时完成?

如果我在 main 方法中启动一个新线程,然后 main 方法完成,但另一个线程继续工作,则应用程序仍将处于运行状态,直到所有线程都终止,不是吗?

谢谢&圣诞快乐!

When does a typical Java app finish?

If I start a new thread in the main method and then the main method finishes, but the other thread continues working, the app would still be on until all it's threads have died, wouldn't it?

Thanks & Merry Christmas!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掌心的温暖 2024-10-16 11:42:41

是的,除非它是守护线程。引用线程API

当Java虚拟机启动时,通常有一个非守护线程(它通常调用某个指定类的名为main的方法)。 Java 虚拟机继续执行线程,直到发生以下任一情况:

  • 已调用类 Runtime 的退出方法,并且安全管理器已允许进行退出操作。
  • 所有非守护线程的线程都已死亡,原因可能是从 run 方法的调用中返回,或者抛出传播到 run 方法之外的异常。

Yes, unless it's a deamon thread. Quoting from Thread API:

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.
伴我心暖 2024-10-16 11:42:41

main() 函数定义您的主用户线程。您可能还创建了其他用户线程。您可能还对其中一些线程调用了 setDeamon()。

JVM 将在以下情况下结束:

  1. 主例程结束并且没有其他非守护线程
  2. 主线程中有未捕获的异常并且没有其他非守护线程
  3. System.exit() 或 Runtime.halt() 被调用
  4. 内部 JVM 错误(罕见)
  5. Kill -9 信号
  6. 来自操作系统电源故障或类似的不可恢复的硬件故障的

The main() function defines your main user thread. You might have other user threads that you created as well. You might also have called setDeamon() on some of those threads.

The JVM will end when:

  1. The main routine ends and there are no other non-deamon threads
  2. You have an uncaught Exception in the main thread and there are no other non-deamon threads
  3. System.exit() or Runtime.halt() is called
  4. Internal JVM error (rare)
  5. Kill -9 signal from OS
  6. Power failure or similar non-recoverable hardware failure
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文