Why does a thread outlive the main method in Java?

前端 未结 6 2042
小蘑菇
小蘑菇 2020-12-08 14:19

I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The r

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 14:26

    If you want your program to exit when the main method finished, consider making your threads daemons. But take care of the fact, that daemon threads will be aborted, when main finishes.
    You can create a daemon thead like so:

    Thread t = new Thread(...);
    t.setDaemon(true);
    

    All non-daemon threads are user threads. Those threads are stopping the jvm from closing.

提交回复
热议问题