"Daemon thread"是为提供普通服务在后台运行,跟寄主程序同样生命的,却不属于寄主程序的一个线程。寄主程序(non-daemon thread)一但终止,整个程序也就结束了,即使"Daemon thread"还没有运行到结尾.也就是说non-daemon thread终止,daemon thread也终止。
下面例子是引用自tij4的:
[quote]
下面例子是引用自tij4的:
[quote]
package org.iteye.bbjava.concurrency.daemon;
import java.util.concurrent.TimeUnit;
public class SimpleDaemons implements Runnable {
@Override
public void run() {
try {
while (true) {
TimeUnit.MICROSECONDS.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
}
} catch (InterruptedException e) {
System.out.println("sleep interrupted!");
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread daemon = new Thread(new SimpleDaemons());
daemon.setDaemon(true);
daemon.start();
}
System.out.println("All daemon started!");
TimeUnit.MILLISECONDS.sleep(175);
}
}
[/quote]