class DaemonThread implements Runnable{
public DaemonThread(){
System.out.println("Constructor of DaemonThread");
}
public void run(){
for(int i = 0; i <= 100; i++){
System.out.println(i);
try{
Thread.sleep(250);
} catch (InterruptedException e){
System.out.println("Thread Interrupted.");
}
}
}
}
public class UserThread{
public static void main(String args[]){
Thread t = new Thread(new DaemonThread());
//t.setDaemon(true);
t.start();
try{
Thread.sleep(5000);
}catch(InterruptedException e){
System.err.println(e);
}
}
}
If you run this program as it is, it will print from 0 to 100. Now if you remove the comment from the bold statement in the UserThread class, and again compile and run the UserThread class, the output will be from 0 to around 20 (depending upon the processor speed). The output will never be up to 100 as the 慺or?loop is running in the daemon thread. And we have learnt that daemon threads live only till there are other existing user threads.
If you find this useful, email me at schandra_indya@hotmail.com