Friday, August 31, 2012

Thread Concept Part-IV


Daemon Thread

Daemon thread is like a service providers for other threads or objects running in the same process. It is used for background supporting tasks. It is only needed while normal threads are executing.

Points need to remember –

                           i.   Daemon thread is like a service thread for other running threads.

                         ii.   setDaemon(true/false) method is used to set as a daemon thread.

                        iii.   isDaemon() method returns is this thread demon or not by returning true or false .

 

Daemon Thread Example:

§  Demon thread class (file name: DaemonMyThread.java)

public class DaemonMyThread extends Thread {

 

public void run() {

       System.out.println("START main Method: "

                   + Thread.currentThread().getName());

 

       for (int i = 0; i < 5; i++) {

             try {

                   Thread.sleep(500);

             } catch (InterruptedException x) {}

 

             System.out.println(Thread.currentThread().getName()

                         + " running.....");

       }

       System.out.println("STOP main Method: "

                   + Thread.currentThread().getName());

}

 

public static void main(String[] args) {

       System.out.println("START main Method: "

                   + Thread.currentThread().getName());

 

       DaemonMyThread t = new DaemonMyThread();

       t.setDaemon(true);

       t.start();

 

       try {

             Thread.sleep(3000);

       } catch (InterruptedException x) {}

 

       System.out.println("STOP main method: "

                   + Thread.currentThread().getName());

}

}

 

§  Run and see output

START main Method: main

START main Method: Thread-0

Thread-0 running.....

Thread-0 running.....

Thread-0 running.....

Thread-0 running.....

Thread-0 running.....

STOP main Method: Thread-0

STOP main method: main

 

No comments:

Post a Comment