2010-08-21 79 views

回答

11

如果使用System.exit()。無論它們是否守護,所有線程都會停止。

否則,JVM將自動停止由Thread.setDaemon(true)設置的後臺進程線程的所有線程。換句話說,只有剩餘的線程都是守護線程或根本沒有線程時,jvm纔會退出。

考慮下面的例子,即使主方法返回後,它仍會繼續運行。 但是如果你將它設置爲守護進程,它將在主方法(主線程)終止時終止。

public class Test { 

    public static void main(String[] arg) throws Throwable { 
     Thread t = new Thread() { 
      public void run() { 
      while(true) { 
       try { 
        Thread.sleep(300); 
        System.out.println("Woken up after 300ms"); 
       }catch(Exception e) {} 
      } 
      } 
     }; 

     // t.setDaemon(true); // will make this thread daemon 
     t.start(); 
     System.exit(0); // this will stop all threads whether are not they are daemon 
     System.out.println("main method returning..."); 
    } 
} 
3

如果您希望在退出時正常停止線程,Shutdown Hooks可能是一種選擇。

的樣子:

Runtime.getRuntime().addShutdownHook(new Thread() { 
    public void run() { 
    //Stop threads } 
}); 

參見:hook-design