All ITKnowledge Source Code Search Tips Advanced Search |

| Mastering Java Threads by Marc Adler and David Herst DDC Publishing, Inc. ISBN: 1562438425 Pub Date: 05/01/99

Search this book:

Previous | Table of Contents | Next

## Chapter 6
Daemon Threads

Lesson Topics

  • What are Daemon Threads?
  • An Example of Daemon Threads

### What are Daemon Threads?

The UNIX operating system has always had the concept of a daemon process. A daemon process is typically defined as a process that “sits in the background” and waits for some event to occur. When that event does occur, the daemon process “wakes up” and performs some action.

#### UNIX Daemon Process = Java Daemon Thread

Java extends the concept of daemon processes to threads. A daemon thread is a thread that provides services to other threads. The run() method of a daemon thread typically runs in an infinite loop.

Daemon Thread Properties

You can turn a thread’s “daemon” property on or off by calling the thread’s setDaemon() method. If you pass true to setDaemon(), the thread will turn into a daemon. You must call setDaemon() before you call the thread’s start() method.

You can also use the isDaemon() method to test if a thread is a daemon.

| You should not use the destroy() method of the Thread class to terminate a thread. The destroy() method does not perform any cleanup code, and any locks which are engaged will remain locked after destroy() has performed its work.

The Java interpreter will run a program while there is at least one non-daemon thread that exists.

| You must call setDaemon() before you call the thread’s start() method.

### An Example of Daemon Threads

The following code illustrates a Java Applet that uses a daemon thread. In this Applet, random rectangles are drawn within an AWT panel container. There are two buttons that the user can click:

  • the Color button changes the color of subsequent rectangles to a random color.
  • the Stop button terminates the drawing thread.

This example uses a daemon thread to monitor the states of the two pushbuttons. The daemon thread services the main drawing thread by controlling the value of a shared resource (the color).

Figure 6-1 Example of a Java applet that uses a daemon thread

The following code, beginning on the next page, is behind the above example.

    //  daemon.java

    //    Written by Marc Adler/Magma Systems

    import java.applet.*;

    import java.awt.*;

    class Daemon extends Applet implements Runnable

    {

      Thread m_drawingThread = null;

      DaemonThread m_daemonThread = null;

      // The states of the two pushbuttons.

      // These states are monitored by the daemon.

      boolean m_bInterrupted = false;

      boolean m_bChangeColor = false;

      // A global color. The color which the rect will be drawn with

      Color m_color =

       new Color((float) Math.random(),

                 (float) Math.random(),

                 (float) Math.randomo());

      // The UI controls

      Button m_btnStop;

      Button m_btnColor;

      Panel m_panelDrawing;

      public void start ()

    {
        BorderLayout layout = new BorderLayouto ();

        setLayout(layout);

      // Create the controls for the UI. A drawing area & two buttons

      m_btnStop = new Button(“Stop”);

      m_btnColor = new Button(“Color”);

      m_panelDrawing = new Panel();

      add(“North”, m_btnStop);

      add(“South”, m_btnColor);

      add(“Center”, m_panelDrawing);

      m_drawingThread = new Thread (this);

      m_drawingThread.start ();

    }

      public void stop()

      {

        m_drawingThread = null;

      }

      public void run()

      {

        //  Create a daemon to monitor the push button states

        m_daemonThread = new DaemonThread(m_drawingThread);

        m_daemonThread.setDaemon(true);

        m_daemonThread.setPriority(Thread.MAX_PRIORITY - 2);

        m_daemonThread.start ();

        while (m_drawingThread != null)

        {

         // Draw a rectangle and sleep a while

         try

         {

         drawRandomRect ();

         Thread.sleep(200);

      }

      // Catch an interrupt. If we are interrupted,

          // then stop

      catch (InterruptedException e)

      {

        showStatus(“INTERRUPTED!!!”);

        m_drawingThread = null;

       }

      }

    }

    public boolean action(Event evt, Object what)

    {

      // This function gets called when a button is pressed.

      if (evt.target == m_btnStop)

      {

       m_bInterrupted = true;

      }

      else if (evt.target == m_btnColor)

      {

        m_bChangeColor = true;

      }

      return false;

    }

      protected void drawRandomRect ()

      {

       // Draw a random rect within the panel.

       Point pt = new Point ();

       Dimension d = new Dimension ();

       pt.x      =  (int) (Math.random () *

    m_panelDrawing.size () .width);

       pt.y      =  (int) (Math.random () *

    m_panelDrawing.size () .height);

       d.width   =  (int) (Math.random () *

    m_panelDrawing.size() .width);

       d.height  =  (int) (Math.random () *

    m_panelDrawing.size () .height);

       Graphics g = m_panelDrawing.getGraphics ();

       g.setColor (m_color);

       g.fillRect(pt.x, pt.y, d.width, d.height);

     }

      class DaemonThread extends Thread

     {

       Thread m_parentThread = null;

       public DaemonThread(Thread parentThread)

     {

          super ();

          m_parentThread = parentThread;

        }

        public void run ()

       {

          while (true)

      {

        // Let the other threads have a chance.

        try

        {

             Thread.sleep (500);

           }

           catch (InterruptedException e)

           {

           }

           // If the STOP button was pressed,

           //interrupt the drawing thread. if (m_bInterrupted)

           {

              m_parentThread.interrupt ();

           // If the COLOR button was pressed,

         // set a new global color and

         // reset the state of the button

        if (m_bChangeColor)

        {

          m_color = new Color ((float) Math.random (),

                                 (float) Math.random (),

                                 (float) Math.random ());

           m_bChangeColor = false ;

          }

        }

      }

    }

Previous | Table of Contents | Next

Copyright © DDC Publishing

Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.