概念类似于Linux的后台守护进程,JVM的垃圾回收线程就是典型的后台线程,它负责回收其他线程不再使用的内存。只有前台的所有线程结束后后台线程才会结束。main线程默认为前台线程,而由前台线程创建的线程都是前台线程(后台创建的则是后台线程)。
Thread类的setDaemon()方法设置后台线程(线程启动之前),isDaemon()方法判断后台线程。
下边的实例程序我们在主线程中一直将a加1,start方法中创建了一个匿名线程类,它的实例为后台实例,每隔10ms把a重置为0
package org.bupt.test;
public class Machine extends Thread{
private int a;
private static int count;
public void start(){
super.start();
Thread daemon = new Thread(){//创建匿名类的实例
public void run() {
while (true) {//尽管是无限循环,但是在主线程结束时也会结束。
reset();
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void reset() {
a=0;
}
};
daemon.setDaemon(true);
daemon.start();
}
public void run() {
while (true) {
System.out.println(currentThread().getName()+":"+a++);
if (count++==100) {
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
Machine machine=new Machine();
machine.setName("m1");
machine.start();
}
}
责任编辑:小草