When does the main thread stop in Java?

前端 未结 7 2116
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 15:06

I read this statement:

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

7条回答
  •  广开言路
    2020-11-27 15:46

    The JVM will exit when the main thread and all non-daemon threads finish execution.

    When you create a new thread, you can call Thread.setDaemon(true) to make it a daemon thread. If you do this, then the JVM will not wait until this thread finishes before execution. This is useful for any threads you create which are made to run in the background until the program stops.

    If you create a new thread and do not call Thread.setDaemon(true), then the JVM will delay exit until this thread is complete, even if the main thread is finished.

提交回复
热议问题