public class ThreadTest implements Runnable{
public void run() {
while (true) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
System.out.println("==============");
}
}
}
}
public static void main(String[] args) {
Thread daemonThread = new Thread(new ThreadTest());
// 设置为守护进程
daemonThread.setDaemon(true);
daemonThread.start();
/*
System.out.println("isDaemon = " + daemonThread.isDaemon());
Scanner scanner = new Scanner(System.in);
// 接受输入,使程序在此停顿,一旦接受到用户输入,main线程结束,JVM退出!
scanner.next();
//AddShutdownHook方法增加JVM停止时要做处理事件:
//当JVM退出时,打印JVM Exit语句.
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("JVM Exit!");
}
});
*/ }
public void run() {
while (true) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
System.out.println("==============");
}
}
}
}
public static void main(String[] args) {
Thread daemonThread = new Thread(new ThreadTest());
// 设置为守护进程
daemonThread.setDaemon(true);
daemonThread.start();
/*
System.out.println("isDaemon = " + daemonThread.isDaemon());
Scanner scanner = new Scanner(System.in);
// 接受输入,使程序在此停顿,一旦接受到用户输入,main线程结束,JVM退出!
scanner.next();
//AddShutdownHook方法增加JVM停止时要做处理事件:
//当JVM退出时,打印JVM Exit语句.
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("JVM Exit!");
}
});
*/ }
}
当daemonThread.start();之后被注释掉之后,JVM中已经没有非daemon线程了(主线程已经执行完毕),所以不会输出deamon线程中的finally语句;
当不注释时,由于主线程还没有执行完毕,所以会输出deamon线程中的finally语句==============