Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Deamon thread how to

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry but i didn't understand
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so ok .. how can i create one thread that will be allways alive?
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic