When does the main thread stop in Java?(Java中的主线程什么时候停止?)
问题描述
我读了这个声明:
主线程必须是完成执行的最后一个线程.当主线程停止时,程序终止.
The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.
是真的吗?
我也开始知道即使主线程死了,程序也会继续运行".
I also came to know "Even if the main thread dies, the program keeps running".
这是我目前的理解:
- 当您启动一个程序时,JVM 会创建一个线程来运行您的程序.
- JVM 创建一个用户线程来运行程序.这个线程称为主线程.
- 从主线程调用类的
main方法. - 如果程序从主线程产生新线程,程序会一直等待,直到最后一个线程终止.
哪一个是真的?
推荐答案
当所有非守护线程都死掉时程序终止(守护线程是用 setDaemon(true) 标记的线程;通常是用于实用程序线程).来自文档:
The program terminates when all non-daemon threads die (a daemon thread is a thread marked with setDaemon(true); it's usually used for utility threads). From the documentation:
当 Java 虚拟机启动时,通常有一个非守护线程(通常调用某个指定类的名为 main 的方法).Java 虚拟机继续执行线程,直到发生以下任一情况:
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:
- 已调用 Runtime 类的退出方法,并且安全管理器已允许执行退出操作.
- 不是守护线程的所有线程都已死亡,要么从调用 run 方法返回,要么抛出传播到 run 方法之外的异常.
这篇关于Java中的主线程什么时候停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的主线程什么时候停止?
基础教程推荐
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
