Search This Blog

Saturday, December 13, 2014

User Thread and Daemon Thread

User Threads and Daemon Threads :
 
A User thread is a thread that is created by the User i.e, application where as a Daemon thead is a thread
that is created to serve the user thread. Daemon thread usually runs in the background continuously.

Rules to remember:
1. The JVM exits if only threads running are the daemon threads i.e, the JVM does not wait for the daemon threads
unless join() method is called on it
2. The JVM does not call the finally methods of daemon threads
3. Use setDaemon(true) only before calling start() method

Example:

package com.learninjava;

/**
 * @author www.learninjava.com
 */
public class UserAndDaemonThreads {
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
       
        Thread daemonThread = new Thread(new Runnable() {
           
            public void run() {
               
                while ( true ) {
                    System.out.println("In run method of daemon thead...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println("In finally method of daemon thread...");
                    }
                }
               
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();
       
        //daemonThread.join();

        System.out.println("Exiting main thread...");
    }

}

Output:
Exiting main thread...
In run method of daemon thead...

Note: The above output is not guaranteed to be same as shown because the JVM may exit without even printing the S.o.p in while loop

The output of the below example shows that the JVM exits without waiting for the while loop to complete.
Also observe that the statement in finally is not displayed (rule 2).
Uncomment the join() statement and re-run the example. Now you will see that the JVM is waiting for the daemon thread.


For the complete article see User and Daemon Threads on www.learninjava.com

No comments: