守護線程
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:退出