class A implements runnable{ public void run(){ for(;;){ System.out.println("Thread A run"); } } public static void main(String[] args){ System.out.println("Thread main started!"); try{ (new Thread(new A())).start(); } catch (Exception e){ } System.out.println("Thread main ended!"); } }; 会一直跑下去,因为main进程结束了,但 A 进程还没有结束,虚拟机不能退出,class A implements runnable{ public void run(){ for(;;){ System.out.println("Thread A run"); } } public static void main(String[] args){ System.out.println("Thread main started!"); try{ Thread a = new Thread(new A()); a.setDaemon(true); a.start(true); } catch(Exception e){ } System.out.println("Thread main ended!"); } };main 线程一退出,虚拟机就退出了,因为剩下在跑的 a 线程是守护线程,虚拟机不管它的死活的,直接退出了。
虚拟机中可能会同时有很多个线程在运行,只有当所有的非守护线程都结束的时候,虚拟机的进程才会结束,不管在运行的线程是不是 main() 线程。说起来有点拗口,自己去看 java.lang.Thread 中 setDaemon() 的说明吧
public void run(){
for(;;){
System.out.println("Thread A run");
}
} public static void main(String[] args){
System.out.println("Thread main started!");
try{
(new Thread(new A())).start();
} catch (Exception e){
}
System.out.println("Thread main ended!");
}
};
会一直跑下去,因为main进程结束了,但 A 进程还没有结束,虚拟机不能退出,class A implements runnable{
public void run(){
for(;;){
System.out.println("Thread A run");
}
} public static void main(String[] args){
System.out.println("Thread main started!");
try{
Thread a = new Thread(new A());
a.setDaemon(true);
a.start(true);
} catch(Exception e){
}
System.out.println("Thread main ended!");
}
};main 线程一退出,虚拟机就退出了,因为剩下在跑的 a 线程是守护线程,虚拟机不管它的死活的,直接退出了。
还有 a.start(); 不是 a.start(true):
sorry!