java daemon threads

前端 未结 4 1576
春和景丽
春和景丽 2021-01-22 06:45

Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the \"main\" thread will finish?

I tested this example

相关标签:
4条回答
  • The Daemon Thread stopped working due to the fact that there weren't any non-daemon threads left and NOT because the parent thread completed.

    0 讨论(0)
  • 2021-01-22 07:05

    Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the "main" thread will finish?

    A daemon thread will be stopped by the JVM when the main execution thread and all the user threads terminated their execution. Then, your daemon thread is strictly dependent from the execution of the user threads and the main thread of your program.

    Instead, the JVM will shutdown your program until all the user threads have been terminated.

    As recap, the user thread is a thread that keeps a program from quitting, because, even if the main thread of your program is terminated, the JVM doesn't stop your program until all the user threads have completed the requested job. Only when all the user threads have terminated, the JVM can shutdown the program.

    Then, a daemon thread is a thread that doesn't keep your program from quitting. For other info, check this old question of SO.

    Check the Thread API. The documentation for setDaemon() method reports below:

    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 thread.

    Or the Runtime API:

    The Java virtual machine shuts down in response to two kinds of events:

    1) The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

    2) The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

    0 讨论(0)
  • 2021-01-22 07:05

    Since the main thread ends as soon as the simple thread is started, the simple thread is the last application thread to finish, so the daemon thread ends when this thread ends.

    The fact that the simple thread is the one that started the daemon thread has nothing to do with that.

    0 讨论(0)
  • 2021-01-22 07:12

    will daemon thread stop working when the enclosing it thread will finish?

    There's no such concept as an "enclosing thread" in Java. There are thread groups but they're rarely used.

    Daemon threads are simply threads which don't stop the JVM from terminating. When there aren't any non-daemon threads left, the JVM will terminate. If there are still some non-daemon threads executing, the JVM will keep going, including any daemon threads - whether or not the threads that started those daemon threads have finished.

    0 讨论(0)
提交回复
热议问题