![树状图梳理](https://i-blog.csdnimg.cn/blog_migrate/1a9116d853ea3cec96342c440a4d911f.png)
实例
public class 守护线程 {
public static void main(String[] args) {
Thread t=new Thread(new MyRunnable());
Thread workerThread=new Thread(new WorkerRunnable());
t.setDaemon(true);
t.start();
for(int i=0;i<30;i++){
if (i==0) {
System.out.println("按理是此(主函数)线程先于工作线程开始和结束,以及保护线程结束");//第一句输出
}
System.out.print("i="+i+";");
}
System.out.println("");
workerThread.start();
}
}
class MyRunnable implements Runnable{//保护线程
@Override
public void run() {
while (true) {
System.out.println("对工作线程的数据进行处理中...");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {System.out.println("数据处理异常"); }
}
}
}
class WorkerRunnable implements Runnable{//工作线程
int number;
@Override
public void run() {
int number=1;
for(int i=0;i<30;i++){
number+=this.number;
System.out.println("number+=this.number="+number);
this.number=i+1;
System.out.println("this.number="+i+"+1="+(i+1));
System.out.println("工作线程进入休眠状态1秒");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("工作线程休眠异常");
}
}
}
}
运行截图(部分)
![运行截图](https://i-blog.csdnimg.cn/blog_migrate/df126ae19af9e70b73ab88c5257efa66.png)