I have two threads: the main thread and a thread generated from the main thread.
When the main thread exits, will the whole program terminate?
Threads are part of the process. If the process exits, they (along with all other process resources) cease to exist.
Calling the exit subroutine terminates the entire process, including all its threads. In a multithreaded program, the exit subroutine should only be used when the entire process needs to be terminated; for example, in the case of an unrecoverable error.
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.
No.
Java programs terminate when all non-daemon threads finish.
The documentation states:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
- The
exit
method of classRuntime
has been called and the security manager has permitted the exit operation to take place.- All threads that are not daemon threads have died, either by returning from the call to the
run
method or by throwing an exception that propagates beyond therun
method.
If you don't want the runtime to wait for a thread, call the setDaemon
method.
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