主线程何时在Java中停止? [英] When does the main thread stop in Java?

查看:290
本文介绍了主线程何时在Java中停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了这句话:


主线程必须是完成执行的最后一个线程。当主线程停止时,程序终止。


是真的吗?



<我也开始知道即使主线程程序继续运行。



据我所知:当你启动一个程序时,JVM会创建一个线程运行你的程序。 JVM创建一个用于运行程序的用户线程。该线程称为主线程。从主线程调用类的主要方法。如果程序从主线程生成新线程,它会一直停止,直到最后一个线程死亡。



哪一个是真的?

解决方案

程序在所有非守护程序线程死亡时终止(守护程序线程是标有 setDaemon(true)的线程;通常是用于实用程序线程)。来自 javadoc


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




  • 已调用类Runtime的退出方法并且安全管理器允许退出操作发生。

  • 所有非守护程序线程的线程都已经死亡,无论是通过调用run方法返回还是抛出一个超出run方法传播的异常。



I read this statement:

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

Is it true?

I also came to know " Even if the main thread dies program keep running".

As far as my understanding: When you start a program, JVM creates one thread to run your program. The JVM creates one user thread for running a program. This thread is called main thread. The main method of the class is called from the main thread. If program spawns new threads from the main thread, it does stop until last thread dies.

Which one is true?

解决方案

Program terminates when all non-daemon threads die (daemon thread is a thread marked with setDaemon(true); it's usually used for utility threads). From javadoc:

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中停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆