Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

multithreading - Why does a thread outlive the main method in Java?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...