Suppose I jave a Java application which have a Thread running inside it's main method.
after all the code in the main method get executed. would the application wait for the Thread until it finish executing, or it will just terminate the application and the JVM.
From java.lang.Thread documentation:
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.
So, yes, it will wait, but not for threads marked as daemon threads.
You could see it working with the following code:
public class ThreadTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I'm still here!");
}
});
// uncomment following line to test with daemon thread
//thread.setDaemon(true);
thread.start();
System.out.println("Finished!");
}
}
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