守护线程
Java有种线程叫做守护(Deamon)线程。这种线程优先级很低,通常是无限循环的,作为服务提供者。守护线程是的优先级的,而且当程序中只有守护线程时,程序会退出运行。所以守护线程不能做重要的工作,因为它不能保证什么时候被分配到资源,也可能会随时结束。创建守护线程很简单,只要调用Thread类的setDaemon方法即可。下面用守护线程演示一个时钟:
public class DaemonThreadDemo {
public static void main(String[] args){
Thread t = new Thread(new DaemoClock());
System.out.println("main:设置线程是守护线程,并启动");
t.setDaemon(true);
t.start();
try {
System.out.println("main:等待5s");
Thread.sleep(5000);
System.out.println("main:退出");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class DaemoClock implements Runnable{
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName() + ":" + new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
程序运行日志:
main:设置线程是守护线程,并启动
main:等待5s
Thread-0:Wed Apr 16 17:48:50 CST 2014
Thread-0:Wed Apr 16 17:48:51 CST 2014
Thread-0:Wed Apr 16 17:48:52 CST 2014
Thread-0:Wed Apr 16 17:48:53 CST 2014
Thread-0:Wed Apr 16 17:48:54 CST 2014
main:退出