How to create a daemon thread? and what for?
Daemon status must be set before starting the thread
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
First you need to set a thread as daemon just before you start it, so the first thing would be like this:
Thread t = new Thread(new Evil());
t.setDaemon(true);//success is here now
t.start();
Thread.sleep(1000);
Daemon threads are like normal (user) threads, but there is a big difference. The JVM kills (halt) the application when there is no user thread exist (alive), in other word if you have 1 user thread (main thread for example) and 1000 daemon threads, here the JVM sees one thread in your application, and it kills the application just after that main thread finishes its job.
These threads are good for handling or doing some business logic in the background till other user threads alive, and beware about changing anything withing daemon thread, because there is no any signal before halting a thread by JVM.
So in you case, where daemon thread waits for 1 second and say something and again sleep for 1 second, because this is daemon, and main threads is no more after 1 second, then daemon thread never reaches the second sleep line.
This (diagram) may help you too.
- Daemon threads aren't evil (although technically they could do evil things).
- You can't make a thread daemon after it has been started.
- You would use a daemon thread as a background thread that mustn't/doesn't need to prevent the program from closing.
The javadoc for Thread.setDaemon(boolean)
says:
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be called before the thread is started.
A good example for a deamon thread is a timer.
It makes no sense that a timer fires one more time if there are no user threads anymore.