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?
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.
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.
main thread will only wait for 2 seconds to child thread to die and executes its further statements.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With