if main method completes the execution, what happens to any long running thread?

后端 未结 3 706
小鲜肉
小鲜肉 2021-01-17 12:35

since main() runs on a thread. and as soon as the main() finishes, main-thread should stop. So if main() has invoked a long running th

3条回答
  •  借酒劲吻你
    2021-01-17 12:45

    The process will terminate when there are no more non-daemon threads, killing any daemon threads if necessary. However, if you do have any non-daemon threads, those will prevent the process from terminating.

    From Thread.setDaemon:

    Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

    This method must be invoked before the thread is started.

    And from section 12.8 of the JLS:

    A program terminates all its activity and exits when one of two things happens:

    • All the threads that are not daemon threads terminate.

    • Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

提交回复
热议问题