当线程调用 System.exit() 时会发生什么?
到底发生了什么?是线程停止了,还是程序停止了?那我怎样才能停止主线程呢?
What exactly occurs? Does the thread stop, or does the program stop? How can I stop the main thread then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您的意思是
System.exit
(或Runtime.exit
) 调用,它具有终止整个 JVM 的效果,无论哪个线程调用它。各个线程仅在其“run”方法终止时才停止,对于主线程来说,这是一个 main 方法;但是,当该线程停止时,JVM 也会停止,除非有任何非 守护进程线程正在运行。因此,要“停止”主线程而不终止 JVM,您可以在 main 方法终止之前创建并启动另一个线程。
I assume you mean the
System.exit
(orRuntime.exit
) call, which has the effect of terminating the entire JVM, regardless of which thread calls it.Individual threads are only stopped when their "run" method terminates, and in the case of the main thread, this is a main method; however, when this thread stops then so does the JVM, unless there is any non-daemon thread running. So to "stop" the main thread without terminating the JVM you can create and start another thread before the main method terminates.
当您从其
run()
方法返回
时,线程将停止。主线程只是另一个线程(尽管有点特殊),您可以从
main()
返回,也可以调用System.exit()
来停止 JVM。编辑:上面的内容有点混乱,如下面的评论所述。
请注意,通过从主线程返回来停止主线程不会自动停止其他线程,并且 JVM 将继续运行它们,直到它们停止或您终止 JVM 进程。
The thread stops when you
return
from itsrun()
method.The main thread is just another thread (albeit slightly special), you either return from
main()
or you callSystem.exit()
to stop the JVM.Edit: The above is a little muddy, as noted in the comment below.
Note that stopping the main thread by returning from it doesn't automatically stop your other threads, and the JVM will continue to run them until they stop or you kill the JVM process.