从结果可以看出 "守护线程第" + i + "次执行!" 并没有执行50次(这时因为 “当开始守护线程的主线程退出时,守护线程自动退出”)。
public class ThreadDemo{
/**
* @param args
*/
public static void main(String[] args) {
Thread t1 = new CommonThread();
Thread t2 = new Thread(new DaemonThread());
t2.setDaemon(true); //设置为守护线程
t2.start();
t1.start();
}
}
................................................................................................
public class CommonThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("普通线程1第" + i + "次执行!");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
...................................................................................................
public class DaemonThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("守护线程第" + i + "次执行!");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}