JAVA后台线程的特点是只有所有的前台线程结束运行,后台线程才能结束,后台线程可用setDaemon()进行设置:
1 package withdaemon; 2 3 public class Machine extends Thread { 4 private int a; 5 private static int count; 6 7 public void start() { 8 super.start(); 9 Thread deamon=new Thread() { 10 public void run() { 11 while(true) { 12 reset(); 13 try { 14 sleep(1000); 15 } catch (InterruptedException e) {throw new RuntimeException(e);} 16 } 17 } 18 }; 19 deamon.setDaemon(true); 20 deamon.start(); 21 } 22 23 public void reset() {a=0;} 24 public void run() { 25 while (true) { 26 System.out.println(getName()+":"+a++); 27 if (count++==100) break; 28 yield(); 29 } 30 } 31 /** 32 * @param args 33 */ 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 Machine machine=new Machine(); 37 machine.start(); 38 } 39 }