Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
John Humphreys Avatar asked Dec 16 '12 19:12

John Humphreys


People also ask

Why is it important for the main thread to terminate at the end?

There are certain properties associated with the main thread which are as follows: It is the thread from which other “child” threads will be spawned. Often, it must be the last thread to finish execution because it performs various shutdown actions.

What happens if main thread exits Java?

As long as the main-method thread or any other user thread remains alive, your application will continue to execute. In your case, the threads are user threads and hence are allowed to complete before the main thread exits.

Can main thread dies before the child thread?

main thread will only wait for 2 seconds to child thread to die and executes its further statements.

Does a thread automatically be killed?

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.


1 Answers

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.

like image 177
JB Nizet Avatar answered Sep 28 '22 15:09

JB Nizet