當前台線程結束后,jvm將直接殺死后台線程,並且后台線程不會去執行finally代碼塊中的內容
public class DemoThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.currentThread().sleep(1000);
System.out.println("我是非守護線程");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
public class Main {
public static void main(String[] args) {
threadStart();
}
public static void threadStart(){
DemoThread dt = new DemoThread();
Thread thread = new Thread(dt);
thread.setDaemon(true);
thread.start();
}
}
1、當直接啟動時,不會打印出內容
2、當去掉thread.setDaemon(true)時,會打印出“我是非守護線程”
原因分析:當thread設置為守護線程時,主線程是前台線程,執行完之后就直接結束,jvm直接kill啦thread這個守護線程,這個守護線程中的內容就不會繼續執行下去;當去掉那一行時,thread就默認時前台線程,jvm會等所有前台線程執行完之后才會結束,thread線程即打印出啦內容
