Create a Daemon Thread in Java

Description

The following code shows how to create a Daemon Thread.

A daemon thread is a background thread.

It is subordinate to the thread that creates it. When the thread that created the daemon thread ends, the daemon thread dies with it.

A thread must be marked as a daemon thread before it is started. A live daemon thread does not prevent an application from exiting.

Example


/* w  w  w .j  a  va 2 s  .  c o m*/

class MyDaemon implements Runnable {
  Thread thrd;
  MyDaemon() {
    thrd = new Thread(this);
    thrd.setDaemon(true);
    thrd.start();
  }
  public boolean isDaemon(){
    return thrd.isDaemon();
  }
  public void run() {
    try {
      while(true) {
        System.out.print(".");
        Thread.sleep(100);
      }
    }
    catch(Exception exc) {
      System.out.println("MyDaemon interrupted.");
    }
  }
}

public class Main {
  public static void main(String args[]) throws Exception{
    MyDaemon dt = new MyDaemon();
    if(dt.isDaemon())
      System.out.println("dt is a daemon thread.");

    Thread.sleep(10000);
    System.out.println("\nMain thread ending.");
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Thread »




Data Structure
Semaphore
Thread