When does the main thread stop in Java?

前端 未结 7 2087
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 15:06

I read this statement:

The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.

7条回答
  •  一生所求
    2020-11-27 15:54

    I read this statement: “The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.”Is it true?

    No, it is not. The virtual machine terminates if the last non-daemon thread has finished. It doesn't have to be the main thread.

    Simple example:

    public static void main(String[] args) {
    
       System.out.println("Main thread started");
       new Thread(new Runnable() {
         @Override
         public void run() {
            System.out.println("Second thread started");
            try {
              Thread.sleep(2000);  // wait two seconds
            } catch(Exception e){}
            System.out.println("Second thread (almost) finished");
         }
       }).start();
       System.out.println("Main thread (almost) finished");
    }
    

提交回复
热议问题