网上找的一个简单的守护进程。守护线程与其他线程的区别是,如果守护线程是唯一运行着的线程,程序会自动退出。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* java 的守护进程示例,当任务执行完毕,守护进程运行结束
* @author ahomeeye
*/
//主任务类
public class Daemon {
public static void main(String[] args) {
Thread d = new Daemons();
System.out.println("d.isDaemon() = " + d.isDaemon());
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting for CR");
try {
stdin.readLine();
} catch (IOException e) {
}
}
}
//主线程类
class Daemons extends Thread {
private static final int SIZE = 10;
private Thread[] t = new Thread[SIZE];
public Daemons() {
setDaemon(true);
start();
}
public void run() {
for (int i = 0; i < SIZE; i++) {
t[i] = new DaemonSpawn(i);
}
for (int i = 0; i < SIZE; i++) {
System.out.println("t[" + i + "].isDaemon() = " + t[i].isDaemon());
}
while (true) {
yield();
}
}
}
//子线程类
class DaemonSpawn extends Thread {
public DaemonSpawn(int i) {
System.out.println("DaemonSpawn " + i + " started");
start();
}
public void run() {
while (true) {
yield();
}
}
}