Deamon threads

public class DeamonThreads {

  public static void main(String[] args) {
    System.out.println(threadName() + " started");
    Thread sleepingThread = sleepingThread();
    sleepingThread.setDaemon(true);
    sleepingThread.start();
    System.out.println(threadName() + " finished");
  }

  private static Thread sleepingThread() {
    return new Thread(new Runnable() {

      @Override
      public void run() {
        out.println(threadName() + " started");
        sleepSeconds(5);
        out.println(threadName() + " finished");
      }
    });
  }

  private static void sleepSeconds(int n) {
    try {
      Thread.sleep(1000 * n);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }


  private static String threadName() {
    return second()+":"+currentThread().getName()+":";
  }

  private static String second() {
    long currentTimeMillis = currentTimeMillis();
    long value = currentTimeMillis / 1000;
    return "Second " + (value - (value / 100 * 100));
  }
}

Result:
Second 0:main: started
Second 0:Thread-0: started
Second 0:main: finished

Thread-0 is started as deamon thread by main thread. Deamons are immediately killed when main finishes.

If we set Thread-0 to non deamon, then the non deamon continues to run even if main thread finished:
Second 0:main: started
Second 0:Thread-0: started
Second 0:main: finished
Second 5:Thread-0: finished

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s