Why does a thread outlive the main method in Java?

前端 未结 6 2046
小蘑菇
小蘑菇 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:44

    The Java Language Specification section 12.8 indicates:

    12.8. Program Exit

    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.

    This means it is not enough for the main thread to finish.

    If you do want it to exit when the main thread ends you need to either make the new thread a daemon by using Thread#setDaemon or use Thread#join as you initially suggested.

提交回复
热议问题