top examplets

Daemon Threads

An application doesn't end until every non-daemon thread in it has stopped. So how do you make a deamon thread?

Non-Daemon Thread


// ThreadDemo1.java


// Spawn a non-daemon thread that takes a while to get done.  The
// application does not end until the thread has finished.

class ThreadDemo1 extends Thread
  {


  // Main.  Start the thread, then count to five.

  public static void main (String[] args)
    {
    Thread thread = new ThreadDemo1();
    thread.start();
    for (int i = 0; i < 5; i++)
      {
      System.out.println ("Main: " + i);
      sleep (1000);
      }
    System.out.println ("Main done");
    }


  // This method is run as a separate thread.  Count to 10.

  public void run()
    {
    for (int i = 0; i < 10; i++)
      {
      System.out.println ("Thread: " + i);
      sleep (1000);
      }
    System.out.println ("Thread done");
    }


  // Sleep for so-many milliseconds.

  static void sleep (int msec)
    {
    try
      {Thread.currentThread().sleep (msec);}
    catch (InterruptedException e)
      {}
    }


  };

See also


Daemon thread


// ThreadDemo2.java


// Spawn a daemon thread that takes a while to get done.  The application
// ends as soon as the main thread ends, even though the daemon thread is
// not done.

class ThreadDemo2 extends Thread
  {


  // Main.  Start the thread, then count to five.

  public static void main (String[] args)
    {
    Thread thread = new ThreadDemo2();
    thread.setDaemon (true);
    thread.start();
    for (int i = 0; i < 5; i++)
      {
      System.out.println ("Main: " + i);
      sleep (1000);
      }
    System.out.println ("Main done");
    }


  // This method is run as a separate thread.  Count to 10.

  public void run()
    {
    for (int i = 0; i < 10; i++)
      {
      System.out.println ("Thread: " + i);
      sleep (1000);
      }
    System.out.println ("Thread done");
    }


  // Sleep for so-many milliseconds.

  static void sleep (int msec)
    {
    try
      {Thread.currentThread().sleep (msec);}
    catch (InterruptedException e)
      {}
    }


  };

The Applications' Outputs

ThreadDemo1      ThreadDemo2
(Non-daemon)      (Daemon)
------------     -----------
Main: 0          Main: 0
Thread: 0        Thread: 0
Main: 1          Main: 1
Thread: 1        Thread: 1
Main: 2          Main: 2
Thread: 2        Thread: 2
Main: 3          Main: 3
Thread: 3        Thread: 3
Main: 4          Main: 4
Thread: 4        Thread: 4
Main done        Main done
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread done

Copyright (c) 1997, 1998 by Wayne E. Conrad, All Rights Reserved
Last Updated May 6, 1998
This page has been accidentally visited times since May 1st, 1998.
HTML DTD Validated Best Viewed With Any Browser

This page hosted by Get your own Free Home Page