Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[ A good finding ] - User & Deamon Threads

 
Vijay Pawar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The above code completes the ChildThread even if the main method completes earlier. The program ends only when the ChildThread completes its run method. Here the ChildThread created is a user thread.
If we call t.setDaemon(true) before calling t.start then the ouptput is :
C:\test>java ThreadTest
This is main thread
now ending main
Child Thread: 1
This means that the child thread does not complete the run method and is killed when the main method terminates.

In the above example, t is a daemon thread and t1 is a user thread. Even if main method completes, since t1 is a user thread it will continue to execute. Hence in this case the daemon thread t will not be killed. The daemon thread is killed by the JVM only if its parent thread is killed. The killing is invoked by the completion of parent thread. But since the user thread t1 is alive, the parent main thread will remain alive ( program will not terminate ) till the user thread completes.

In this example the UserThread counts upto 20 but the Daemon Thread counts only upto 10 and then by this time the User thread has completed ( 500 ms sleep time) and also the main thread has completed, hence now there are no more user thread alive and hence the daemon will be killed forcefully by the JVM.
 
Narasimha Rao B.
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jughead,
Nice examples and explanations....

Thanks...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic