⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 06-01.html

📁 master java threads
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<P><BR></P>
<H2><A NAME="Heading1"></A><FONT COLOR="#000077">Chapter 6<BR>Daemon Threads
</FONT></H2>
<P><BIG><B>Lesson Topics</BIG></B></P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;What are Daemon Threads?
<DD><B>&#149;</B>&nbsp;&nbsp;An Example of Daemon Threads
</DL>
<H3><A NAME="Heading2"></A><FONT COLOR="#000077">What are Daemon Threads?</FONT></H3>
<P>The UNIX operating system has always had the concept of a <I>daemon process</I>. A daemon process is typically defined as a process that &#147;sits in the background&#148; and waits for some event to occur. When that event does occur, the daemon process &#147;wakes up&#148; and performs some action.</P>
<H4 ALIGN="LEFT"><A NAME="Heading3"></A><FONT COLOR="#000077">UNIX Daemon Process = Java Daemon Thread</FONT></H4>
<P>Java extends the concept of daemon processes to threads. A <I>daemon thread</I> is a thread that provides services to other threads. The <B><SMALL>run()</SMALL></B> method of a daemon thread typically runs in an infinite loop.</P>
<P><FONT SIZE="+1"><B>Daemon Thread Properties</B></FONT></P>
<P>You can turn a thread&#146;s &#147;daemon&#148; property on or off by calling the thread&#146;s <B>setDaemon()</B> method. If you pass <B>true</B> to <B>setDaemon()</B>, the thread will turn into a daemon. You must call <B>setDaemon()</B> <I>before</I> you call the thread&#146;s <B>start()</B> method.</P>
<P>You can also use the <B>isDaemon()</B> method to test if a thread is a daemon.</P>
<TABLE WIDTH="90%"><TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/06-01i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT">You should not use the <B>destroy()</B> method of the Thread class to terminate a thread.<BR><BR>The <B>destroy()</B> method does not perform any cleanup code, and any locks which are engaged will remain locked after <B>destroy()</B> has performed its work.</TD>
</TR>
</TABLE>
<P>The Java interpreter will run a program while there is at least one non-daemon thread that exists.
</P>
<TABLE WIDTH="90%"><TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/06-02i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT">You must call <B>setDaemon()</B> <I>before</I> you call the thread&#146;s <B>start()</B> method.</TD>
</TR>
</TABLE>
<H3><A NAME="Heading4"></A><FONT COLOR="#000077">An Example of Daemon Threads</FONT></H3>
<P>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:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;the <B>Color</B> button changes the color of subsequent rectangles to a random color.
<DD><B>&#149;</B>&nbsp;&nbsp;the <B>Stop</B> button terminates the drawing thread.
</DL>
<P>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).
</P>
<P><A NAME="Fig1"></A><A HREF="javascript:displayWindow('images/06-01.jpg',600,436)"><IMG SRC="images/06-01t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/06-01.jpg',600,436)"><FONT COLOR="#000077"><B>Figure 6-1</B></FONT></A>&nbsp;&nbsp;Example of a Java applet that uses a daemon thread</P>
<P>The following code, beginning on the next page, is behind the above example.
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
//  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(&#147;Stop&#148;);

  m_btnColor = new Button(&#147;Color&#148;);

  m_panelDrawing = new Panel();

  add(&#147;North&#148;, m_btnStop);

  add(&#147;South&#148;, m_btnColor);

  add(&#147;Center&#148;, 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(&#147;INTERRUPTED!!!&#148;);

    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 ;

      }

    }

  }

}
</PRE>
<!-- END CODE //-->
</TD></TR>
</TABLE>

<P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch05/05-01.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch07/07-01.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>

<hr width="90%" size="1" noshade><div align="center"><font face="Verdana,sans-serif" size="1">Copyright &copy; <a href="/reference/ddc00001.html">DDC Publishing</a></font></div>
<!-- all of the reference materials (books) have the footer and subfoot reveresed --><!-- reference_subfoot = footer --><!-- reference_footer = subfoot --><!-- BEGIN SUB FOOTER -->	<br>	<img src="/images/dotclear.gif" width="5" height="7" border="0">	</TD>    </TR>	</TABLE>		<table width="100%" border="0" cellspacing="0" cellpadding="0">	<tr>		<td align="left" width="160"><img src="/images/bot_curve.jpg" width="160" alt="" border="0"></td>		<td align="left" valign="top" nowrap><a href="/"><img src="/images/top_tabs/home_bot.gif" alt="home" border="0"></a><!-- <a href="/content/corp.html"><img src="/images/top_tabs/subscribe_bot.gif" alt="Subscribe" border="0"></a> --><a href="/search/"><img src="/images/top_tabs/search_bot.gif" alt="search" border="0"></a><a href="/faq/faq.html"><img src="/images/top_tabs/faq_bot.gif" alt="faq" border="0"></a><a href="/sitemap.html"><img src="/images/top_tabs/sitemap_bot.gif" alt="sitemap" border="0"></a><a href="/contactus.html"><img src="/images/top_tabs/contact_us_bot.gif" alt="contactus" border="0"></a><img src="/images/dotclear.gif" width=260 height="1" alt="" border="0"></td> 	</tr></table>	<table width="100%" bgcolor="#003366" border=0 cellpadding=0 cellspacing=0>		<tr>		<td align="left" width=145><img src="/images/dotclear.gif" width=145 height="1" alt="" border="0"></td>				<!-- END SUB FOOTER -->
<!-- all of the books have the footer and subfoot reveresed --><!-- reference_subfoot = footer --><!-- reference_footer = subfoot --><!-- FOOTER -->			<td align="left" bgcolor="#003366"><table border="0" cellspacing="10" cellpadding="5"><tr><td align="center"><font face="arial, helvetica" size="1" color="#cccccc"><b><a href="/products.html"><font color="#0099CC">Products</font></a>&nbsp;|&nbsp;<a href="/contactus.html"><font color="#0099CC">Contact Us</font></a>&nbsp;|&nbsp;<a href="http://www.earthweb.com/dlink.corp|about_us-jhtml.72.0.-.0.jhtml" target="resource window"><font color="#0099CC">About Us</font></a>&nbsp;|&nbsp;<a href="http://www.earthweb.com/dlink.corp|privacy-jhtml.72.0.-.-.jhtml" target="resource window"><font color="#0099CC">Privacy</font></a>&nbsp;|&nbsp;<a href="http://www.itmarketer.com/" target="resource window"><font color="#0099CC">Ad Info</font></a>&nbsp;|&nbsp;<!--<a href="/consortia/"><font color="#0099CC">Consortia</font></a>&nbsp;|&nbsp;--><a href="/"><font color="#0099CC">Home</font></a></b><br><br>Use of this site is subject to certain <a href="/agreement.html"><font color="#0099CC">Terms &amp; Conditions</font></a>, <a href="/copyright.html"><font color="#0099CC">Copyright &copy; 1996-2000 EarthWeb Inc.</font></a> All rights reserved.  Reproduction in whole or in part in any form or medium without express written <a href="http://www.earthweb.com/dlink.corp|permissions-jhtml.72.0.-.-.jhtml" target="resource window"><font color="#0099CC">permission</font></a> of EarthWeb is prohibited. Read EarthWeb's <A HREF="http://www.earthweb.com/dlink.corp|privacy-jhtml.72.0.-.-.jhtml" target="resource window"><font color="#0099CC">privacy</font></A> statement.</font><br><br></td></tr></table><a href="AITK1a2b3c4d5e6f7g8h9idefcon4.html"><img src="/images/dotclear.gif" border="0" height="1" width="1" align="left"></a></td>		</tr></table><!--DoubleClick Ad BEGIN--><SCRIPT LANGUAGE="JavaScript"><!--document.write('<layer src="http://ad.doubleclick.net/adl/academic.itknowledge.com/homepage;cat=homepage;cat=enterprise;cat=education;cat=it_training;ord=' + ord + '" width="468" height="60" visibility="hide" onload="moveToAbsolute(ph1.pageX, ph1.pageY); visibility=\'show\';" clip="468,60"></layer>');document.write('<LAYER SRC="http://ad.doubleclick.net/adl/itkaca.earthweb.dart/b_aca_soft_dev;a=b_aca_soft_dev4;sz=160x60;ord=' + ord + '" width=160 height=60 visibility="hidden" onLoad="moveToAbsolute(layer1.pageX,layer1.pageY);clip.height=60;clip.width=160; visibility=\'show\';"></LAYER>');//--></SCRIPT> <!--DoubleClick Ad END--></BODY></HTML><!-- END FOOTER -->

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -