Another way to rephrase the question is, is the main thread the last thread to exit?
The theoretical analysis
When you start a Java Application, the system creates a process, allocates resources, and the process starts the Main thread.
We usually refer to the Main thread as the Main thread because other threads are usually started by the Main thread.
But at the process level,main is actually a normal thread. It’s just that some other threads are started by Main.
We can guess: normally, the main thread starts other threads, and they execute separately, unaffected by each other.
Why you should guess: Because the operating system allocates resources in units of processes, even if the main thread exits, the process remains. From the process’s point of view, threads should be flat, with no parent-child relationship.
Practice verification
We simulate the example of a thread pool, starting a thread pool from the main thread, and having the main thread throw an exception when an exception occurs to see if the pool continues to run.
Since there is some online debate that printing does not tell if the main thread has terminated, our example uses exception termination and uses the JConsole tool to verify.
public class ThreadPoolException {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
public static void main(String[] args) {
ThreadPoolException t = new ThreadPoolException();
t.futureGet();
}
void futureGet(a) {
for (int i = 0; i < 5; i++) {
Future future = threadPool.submit(() -> {
System.out.println("current thread name" + Thread.currentThread().getName());
Object object = null;
System.out.print("result## " + object.toString());
});
try {
future.get();
} catch (Exception e) {
System.out.println(Thread.currentThread().getName() + "Abnormal");
// Let the main thread wait a little longer for observation.
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// The main thread terminates
throw new RuntimeException(Thread.currentThread().getName() + "Abnormal"); }}}}Copy the code
We can observe this in JConsole:
The thread in the main thread appears and then disappears, and the thread in the thread pool is still in wait state. The same results can be observed by running the code directly in IDEA.
conclusion
- The JVM exits after all non-daemon threads (user threads) have finished executing;
- The main thread is the user thread;
- The JVM does not exit if only the main thread completes execution, meaning the main thread is not necessarily the last thread to exit.
If you want the main thread to exit, all other threads will exit as well. Then you can set all other threads as daemons, setDaemon(true). For thread pools, you can do something manually when the main thread exits. Methods like shutdown.