Tuesday, February 21, 2017

Daemon Thread

Following characteristics defines the daemon threads:
  1. Daemon threads are service provider threads, they provide services to other threads.
  2. These threads dead automatically if the thread to which they are providing service are dead.
  3. These threads never show any output.
  4. They always run in background.

For example assume a scenario where a client side thread needs to display an image, now here some should be there who brings the image from server / database. So, in this case just create a server side daemon thread which will bring image from the server database.
A real example if daemon thread is relay fielding in cricket match, where one man throws the ball to another and he it throws further.

Java’s garbage collector thread is a daemon thread.

There is a method setDaemon(Boolean) to make a thread as a daemon thread.
For example:

package dev21century.threading;
class DThread1 extends Thread
{     
       DThread1(String threadName)
       {
              super(threadName);
       }
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + getName());
          }
       }
}

public class MainThread {

       public static void main(String[] args) {

        DThread1 dthread1 = new DThread1("DaemonThread1");
       
        dthread1.setDaemon(true);
        //marking this thread as a daemon thread
       
        dthread1.start();
            
        for(int i = 0;i<4;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
Thread Name: DaemonThread1
main
Thread Name: DaemonThread1
main
main
Thread Name: DaemonThread1
Thread Name: DaemonThread1
Thread Name: DaemonThread1

Try to run this program many times the output may be different.


No comments:

Post a Comment