1

I was learning daemon thread content from "Think in Java", however, while I tried to run to daemon thread and was expecting some output, it gave me nothing... my programming IDE is Eclipse and operating system is ubuntu13.04... Please let me know what is going on. The following code will output msg if you comment out "t.setDaemon(true);"

public class Practice implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread()+" "+this);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Daemon is working");
    }

    public static void main(String[] args){
        Thread t = new Thread(new Practice());
        t.setDaemon(true);
        t.start();

    }

}
shanwu
  • 1,493
  • 6
  • 35
  • 45
  • possible duplicate of [What is Daemon thread in java](http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java) – synthomat Jan 13 '14 at 00:23
  • 1
    A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. So, your main thread is exiting even though the daemon thread is running in background. – Sage Jan 13 '14 at 00:29

1 Answers1

2

It simply doesnt have time to print the message because main exits too quickly, try to pause for a sec and you will see it

Thread t = new Thread(new Practice());
t.setDaemon(true);
t.start();
Thread.sleep(1000); <--
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • You are right. It creates the daemon thread and exit. Make main thread wait for couple seconds will do the work. Thank you very much ! – shanwu Jan 13 '14 at 02:13