File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

[ A good finding ] - User & Deamon Threads

Vijay Pawar

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....


I agree. Here's the link:
subject: [ A good finding ] - User & Deamon Threads
It's not a secret anymore!