守护线程-setDaemon:将该线程标记为守护线程或用户线程(前台线程),当正在运行的线程都是守护线程时,Java 虚拟机退出。该方法必须在启动线程前调用
1 class StopThread implements Runnable{ 2 private boolean flag = true; 3 public synchronized void run(){ 4 while(flag){ 5 try{ 6 wait();//t0 t1 使用这个方法是强制性唤醒的会发生异常,就执行catch里的代码,然后将标记改为false 7 }catch (InterruptedException e){ 8 System.out.println(Thread.currentThread().getName()+"....."+e); 9 flag = false; 10 } 11 12 System.out.println(Thread.currentThread().getName()+"......++++"); 13 } 14 } 15 public void setFlag(){ 16 flag = false; 17 } 18 } 19 class StopThreadDemo { 20 public static void main(String[] args) { 21 StopThread st = new StopThread(); 22 23 Thread t1 = new Thread(st); 24 Thread t2 = new Thread(st); 25 26 t1.start(); 27 t2.setDaemon(true);//将t2设为守护线程 28 t2.start(); 29 30 31 int num = 1; 32 for(;;){ 33 if(++num==50){ 34 t1.interrupt(); 35 t2.interrupt(); 36 break; 37 } 38 System.out.println("main...."+num); 39 } 40 System.out.println("over"); 41 } 42 }
原文:http://www.cnblogs.com/LO-ME/p/3574616.html