my dog learned polymorphism*
The moose likes Threads and Synchronization and the fly likes Deamon thread how to Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Deamon thread how to " Watch "Deamon thread how to " New topic
Author

Deamon thread how to

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all
im trying to build deamon thread that will stay up and running and will perform task according to events.
im trying to build first simple deamon thread but without success , im fallowing examples but i dont understand why the deamom don't stay
up and running until i kill the app.
here is the examples im following .
http://www.java2s.com/Code/Java/Threads/DaemonThread.htm
http://www.java2s.com/Code/Java/Threads/Daemonthreadsspawnotherdaemonthreads.htm
Pravin Jain
Ranch Hand

Joined: May 20, 2007
Posts: 60
Daemon threads are not supposed to hold up the JVM.
ie. the JVM terminates once all non-daemon threads
have finished. That is the behavioural difference
of daemon threads with non-daemon threads.
If you want to hold up the JVM from your daemon
threads, you may have to ask one of the non-daemon
possibly main thread to join the daemon thread.


The Zen of Java Programming.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
sorry but i didn't understand
Pravin Jain
Ranch Hand

Joined: May 20, 2007
Posts: 60
When you run a java application a main thread is created as a non
daemon thread, besides some other daemon threads like garbage collector.
The JVM(Java Virtual Machine) keeps on running till all non-daemon threads
have finished. ie. till main finishes or if there are other non-daemon
threads which may be created by main or threads created from main.
The JVM would terminate if only daemon threads are alive.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
so ok .. how can i create one thread that will be allways alive?
Pravin Jain
Ranch Hand

Joined: May 20, 2007
Posts: 60
when you create a thread from main and don't set it as daemon
then since you created the instance of thread from main this
thread would also be non-daemon.
correct steps for creating a new Thread would be:

1. define a class which implements Runnable interface.
2. from the main method create an instance of the above class
3. create an instance of Thread using the Runnable instance
4. set up priority, name and any other property of the new thread
except for the daemon property.
5. call the start method on the new thread object.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Deamon thread how to