java 在主线程退出时终止程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5642802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
termination of program on main thread exit?
提问by user496949
I have two threads: the main thread and a thread generated from the main thread.
我有两个线程:主线程和从主线程生成的线程。
When the main thread exits, will the whole program terminate?
当主线程退出时,整个程序会终止吗?
回答by SLaks
No.
不。
Java programs terminate when all non-daemon threads finish.
Java 程序在所有非守护线程完成时终止。
The documentationstates:
该文件规定:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
- The
exit
method of classRuntime
has been called and the security manager has permitted the exit operation to take place.- All threads that are not daemon threads have died, either by returning from the call to the
run
method or by throwing an exception that propagates beyond therun
method.
当 Java 虚拟机启动时,通常会有一个非守护线程(通常调用某个指定类的名为 main 的方法)。Java 虚拟机继续执行线程,直到发生以下任一情况:
exit
类的方法Runtime
已被调用,安全管理器已允许退出操作发生。- 所有不是守护线程的线程都已死亡,要么是从
run
方法调用返回,要么是抛出传播到run
方法之外的异常。
If you don't want the runtime to wait for a thread, call the setDaemon
method.
如果您不希望运行时等待线程,请调用setDaemon
方法。
回答by skY
No. Main Thread is Non-Demon thread, unless your child thread is demon thread, Program will not terminate even if main thread finishes before child thread. You can check that using below sample program.
不是。主线程是非恶魔线程,除非你的子线程是恶魔线程,否则即使主线程在子线程之前完成,程序也不会终止。您可以使用以下示例程序进行检查。
public class app {
public static void main(String[] args) throws InterruptedException {
app2.mt=Thread.currentThread();
app2 t = new app2();
t.start();
System.out.println("Main starts");
Thread.sleep(2000);
System.out.println("Main ends");
}
}
class app2 extends Thread{
static Thread mt;
public void run(){
try {
mt.join();//waits till main thread dies.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("child thread");
}
}