2010-08-21 80 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