Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes [ A good finding ] - User & Deamon Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "[ A good finding ] - User & Deamon Threads " Watch "[ A good finding ] - User & Deamon Threads " New topic
Author

[ A good finding ] - User & Deamon Threads

Vijay Pawar
Greenhorn

Joined: Sep 04, 2003
Posts: 26

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

Joined: Aug 26, 2002
Posts: 205
Hi Jughead,
Nice examples and explanations....

Thanks...


Narasimha
 
Consider Paul's rocket mass heater.
 
subject: [ A good finding ] - User & Deamon Threads
 
Similar Threads
Daemon Threads
daemon Vs User Thread
JVM and Thread Help
How to make a daemon thread
Evidence 4 Main Thread dead after main method exits