Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The run method just prints "Hello World", sleeps for a second, and repeats.

In my main method, I have:

public static void main(String[] args) {
    Thread thread = new Thread(engine);
    thread.start();
    System.out.println("Done.");
}

As I expected, I see "Hello World" and "Done." printed quickly, meaning the main method has reached the end, but what I didn't expect was that the thread I started kept running even after the end of main was reached.

Why does the program continue to execute even after main exits? I would have thought that when main exited the process would terminate and all of the threads would be cleaned up forcefully. Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
572 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because that's how it works. The program exits when System.exit() is called, or when the last non-daemon thread stops running.

And it makes sense. Without this rule, every Java program consisting in just spawning a GUI, for example, would have to wait() infinitely to avoid the program from exiting immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...