Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

termination of program on main thread exit?

Tags:

java

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?

like image 393
user496949 Avatar asked Apr 12 '11 23:04

user496949


People also ask

What happens when main thread exits?

Threads are part of the process. If the process exits, they (along with all other process resources) cease to exist.

Does exit terminate all threads?

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.

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.


1 Answers

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 class Runtime 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 the run method.

If you don't want the runtime to wait for a thread, call the setDaemon method.

like image 60
SLaks Avatar answered Sep 23 '22 02:09

SLaks