我读到了这个声明:
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/