1.setDeamon:API文档说用了这个方法后就将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。可以这么理解,就把守护线程当成是后台线程,当前台线程在运行的时候,后台线程和其他线程一样,也可以抢cpu资源,没什么区别,但是当前台线程结束之后,后台线程不管什么情况,都会结束。 注意:setDeamon需要在线程启动前执行
Demo1:守护线程
class StopThread implements Runnable{
public void run(){
while(true){
System.out.println(Thread.currentThread().getName()+"....run");
}
}
}
class StopThreadDemo{
public static void main(String[] args) {
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
int num = 0;
while(true){
if(num++ == 60){
break;
}
System.out.println(Thread.currentThread().getName()+"......."+num);
}
System.out.println("over");
}
}
如