我是否必须在Java中手动停止线程?

Dav*_*ave 10 java concurrency multithreading

当我的应用程序准备退出时,通过关闭窗口或调用System.exit()方法.我是否必须手动停止我可能创建的线程,或者Java会为我处理这些线程吗?

nai*_*kus 11

在使用System.exit()的情况下.无论它们是否是守护进程,所有线程都将停止.

否则,JVM将自动停止由Thread.setDaemon(true)设置的守护程序线程的所有线程.换句话说,只有当剩下的线程都是守护线程或根本没有线程时,jvm才会退出.

考虑下面的示例,即使在main方法返回后它仍将继续运行.但是如果你将它设置为守护进程,它将在主方法(主线程)终止时终止.

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...");
    }
}
Run Code Online (Sandbox Code Playgroud)