publicclassTestDaemon{publicstaticvoidmain(String[] args){God god =newGod();You you=newYou();Thread thread=newThread(god,"上帝");
thread.setDaemon(true);//用户线程默认为false,设置为true时为守护线程
thread.start();newThread(you,"你").start();System.out.println("主线程");}}classGodimplementsRunnable{@Overridepublicvoidrun(){while(true){System.out.println("上帝一直守护着你");}}}classYouimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <36500; i++){System.out.println("活着");}System.out.println("再见!世界");}}
什么是守护线程守护线程分为用户线程和守护线程虚拟机必须确保用户线程执行完毕虚拟机不用等待守护线程执行完毕应用:如后台记录操作日志,监控内存,垃圾回收等待…设置守护线程.setDaemon(true)public class TestDaemon { public static void main(String[] args) { God god =new God(); You you=new You(); Thread thread= n