📄 02-01.html
字号:
</td>
<td align="left">
<font face="arial, helvetica" size="-1" color="#336633"><b>Mastering Java Threads</b></font>
<br>
<font face="arial, helvetica" size="-1"><i>by Marc Adler and David Herst</i>
<br>
DDC Publishing, Inc.
<br>
<b>ISBN:</b> 1562438425<b> Pub Date:</b> 05/01/99</font> <A HREF="http://www.digitalguru.com/dgstore/product.asp?isbn=1562438425&ac%5Fid=28" TARGET="anotherwindows"><img src="/images/buyit.gif" width=64 height=23 hspace="5" align="middle" alt="Buy It" border="0"></a>
</td>
</tr>
</table>
<P>
<form name="advanced" method="POST" action="http://ewsearch.earthweb.com:80/jsp/k2search/ewintrak2search_p2.jsp" onSubmit=" return checkForQuery(this); ">
<INPUT type="hidden" name="collection" value="corpitk_p2">
<INPUT type="hidden" name="altcoll" value="allbooks_p2">
<INPUT type="hidden" name="hl" value="on">
<INPUT name="sortspec" type=hidden value="score desc">
<INPUT name="fields" type=hidden value="vdkvgwkey score vstitle vsisbn vsauthor vspublisher vspubdate">
<INPUT name="imageprefix" type=hidden value="http://academic.itknowledge.com">
<INPUT name="ssiFolder" type=hidden value="itkaca">
<INPUT name="topics" type=hidden value="itk_academic">
<INPUT type="hidden" name="bookid" value="t_1562438425">
<font face="arial, helvetica" size=2><b>Search this book:</b></font><br>
<INPUT NAME="query" size=25 VALUE=""> <input type="image" width=28 height=23 border=0 value="Go" name="Go" src="/images/go.gif" align=absmiddle>
</form>
<!-- Empty Reference Subhead -->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch01/01-01.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch03/03-01.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H2><A NAME="Heading1"></A><FONT COLOR="#000077">Chapter 2<BR>The Java Thread Class
</FONT></H2>
<P><BIG><B>Lesson Topics</B></BIG></P>
<DL>
<DD><B>•</B> Thread Attributes
<DD><B>•</B> Using Threads
</DL>
<H3><A NAME="Heading2"></A><FONT COLOR="#000077">Thread Attributes</FONT></H3>
<P>The <SMALL>java.lang</SMALL> package contains the implementation of the Thread class. The declaration of Java’s Thread class is as follows:</P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<P><SMALL>public class Thread extends Object implements Runnable</SMALL></P>
</TD></TR>
</TABLE>
<P>The Thread class is derived from the Java <SMALL>Object</SMALL> class; thus, all of <SMALL>Object</SMALL>’s methods can be used with Thread.</P>
<H4 ALIGN="LEFT"><A NAME="Heading3"></A><FONT COLOR="#000077">Thread Attributes</FONT></H4>
<P>A thread has several attributes—or characteristics—that define how it behaves within a Java application, as shown in Table 2-1.
</P>
<TABLE WIDTH="100%" BORDER><TR>
<CAPTION ALIGN="CENTER" VALIGN="BOTTOM"><B>Table 2-1: Thread attributes</B></CAPTION>
</TR>
<TR>
<TH WIDTH="30%" ALIGN="CENTER" VALIGN="TOP">Attribute</TH>
<TH WIDTH="70%" ALIGN="CENTER" VALIGN="TOP">Description</TH>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="CENTER">Thread Body</TD>
<TD VALIGN="TOP" ALIGN="LEFT">Contains the thread’s logic. Implemented in the <B>run()</B> method.</TD>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="CENTER">Thread State</TD>
<TD VALIGN="TOP" ALIGN="LEFT">The state of activation. Is it running? Is it suspended? Has it been destroyed? Is it sleeping?</TD>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="CENTER">Thread Priority</TD>
<TD VALIGN="TOP" ALIGN="LEFT">Tells the Java scheduler when to run the thread in relation to other threads.</TD>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="CENTER">Daemon Thread</TD>
<TD VALIGN="TOP" ALIGN="LEFT">Provides a service for other threads.</TD>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="CENTER">Thread Group</TD>
<TD VALIGN="TOP" ALIGN="LEFT">All threads belong to a thread group. A Thread Group is a Java class which implements the capabilities of a group of related threads.</TD>
</TR>
</TABLE>
<H3><A NAME="Heading4"></A><FONT COLOR="#000077">Using Threads</FONT></H3>
<P>There are two ways of implementing threads within a Java program.
</P>
<DL>
<DD><B>1.</B> Derive a new class from Thread and allocate an instance of it.
<DD><B>2.</B> Derive a new class that implements Runnable and allocate an instance of it. Then create a new thread and pass the thread a reference to the instance of the Runnable class.
</DL>
<TABLE WIDTH="100%">
<TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/02-01i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="95%">If your class must subclass another class (the common example being <I>Applet)</I>, you should derive a new class that implements Runnable, as outlined in Method 2 on the following page.</TD>
</TR>
</TABLE>
<H4 ALIGN="LEFT"><A NAME="Heading5"></A><FONT COLOR="#000077">Method 1</FONT></H4>
<P>Declare a class that extends the standard Java Thread class, as shown below:
</P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
class UIThread extends Thread
{
public void run ()
{
while (1)
{
CheckMouse ();
CheckKeyboard ();
CheckSerialPort ();
}
}
}
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>
<P>To use this thread, you must allocate an instance of UIThread and call the <B>start()</B> method, as shown below.</P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE SNIP //-->
<PRE>
UIThread m_threadUI = new UIThread ();
m_threadUI.start ();
</PRE>
<!-- END CODE SNIP //-->
</TD>
</TR>
</TABLE>
<H4 ALIGN="LEFT"><A NAME="Heading6"></A><FONT COLOR="#000077">Method 2</FONT></H4>
<P>Another way to use a thread is to declare a class that implements the Runnable interface. Then allocate a thread and pass the instance of this Runnable class to the Thread constructor.
</P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
class UIProcess implements Runnable
{
public void run ()
{
while (1)
{
CheckMouse ();
CheckKeyboar ();
CheckSerialPort ();
}
}
}
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>
<P>The following code must appear somewhere in the main program:
</P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE SNIP //-->
<PRE>
UIProcess m_uiProcess = new UIProcess ();
Thread m_thread = new Thread(m_uiProcess);
m_thread.start ();
</PRE>
<!-- END CODE SNIP //-->
</TD>
</TR>
</TABLE>
<P>You will now take your second sample application and convert it into a Java Applet. Using this example, you will see how the Applet’s <B>run()</B> method is used.</P>
<P><B><SMALL>COUNTER3.HTM</SMALL></B></P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
<HTML>
<HEAD>
<TITLE>Counter3</TITLE>
</HEAD>
<BODY>
<applet code=Counter3 width=400 height=200>
</applet>
</BODY>
</HTML>
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>
<P><B><SMALL>COUNTER3. JAVA</SMALL></B></P>
<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
import java.applet.*;
import java.awt.*;
class Counter3 extends Applet implements Runnable
{
Thread m_t1 = new Thread(this, “First Thread");
Thread m_t2 = new Thread(this, “Second Thread");
List m_list;
public void start ()
{
BorderLayout layout = new BorderLayout ();
setLayout (layout);
m_list = new List (10);
add("Center", m_list);
m_tl.start ();
m_t2.start ();
}
public void run ()
{
for (int i = 1; i <= 10; i++)
{
m_list.addItem(Thread.currentThread () .getName () + “: i is ” + i);
}
m_list.addItem(Thread.currentThread () . getName () + “ is finished”);
}
}
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>
<P><A NAME="Fig1"></A><A HREF="javascript:displayWindow('images/02-01.jpg',514,450)"><IMG SRC="images/02-01t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/02-01.jpg',514,450)"><FONT COLOR="#000077"><B>Figure 2-1</B></FONT></A> COUNTER3.JAVA in action</P>
<TABLE WIDTH="100%">
<TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/02-02i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="95%">The sequence of the execution of the threads seems to rotate better than the corresponding console application (which was demonstrated earlier in this course). This topic will be covered later in this course (when the Java scheduler is explained).</TD>
</TR>
</TABLE>
<P><FONT SIZE="+1"><B>Lab 1: Generating Stock Information</B></FONT></P>
<P>This lab exercise will give you an introduction to programming multiple threads in Java. In this course, the subject of the stock market will be used to write a series of applications that relate to this subject.
</P>
<P><B>Need to Generate Data</B></P>
<P>In order to do anything with stocks, you will need to generate some stock data (you could always obtain stock data from the Internet, but this will have to wait for later). Our first application involves generating some fabricated data for a series of stocks of our choosing.</P>
<P>This application will be a Java console application. There is no need for a user interface for the first task, and there is no need to make it an Applet. Therefore, it will be a simple console application.</P>
<P>You will pick <B><I>n</I></B> stocks and write information regarding each stock to a separate file. (A good value for <B><I>n</I></B> is 3). A stock has three characteristics:</P>
<DL>
<DD><B>1.</B> the name of the stock (for example, “MSFT”)
<DD><B>2.</B> the low price in a price range (for example, 110.25)
<DD><B>3.</B> the high price in the price range (for example, 130.875)
</DL>
<P>Define <B><I>n</I></B> stocks and for each stock, create an empty file called STOCK. STK. For instance, if a stock’s symbol is “MSFT,” create an empty file called MSFT.STK. For each stock, generate a series of random prices that fall within the price range and write that price out to the file. Each price should be in ASCII and appear on a separate line. Remember: stock prices are calculated in eighths of a dollar.</P>
<P>For example, the contents of the first few lines of MSFT.STK might appear as follows:</P>
<!-- CODE SNIP //-->
<PRE>
121.375
128
127.25
124.25
122.875
</PRE>
<!-- END CODE SNIP //-->
<P>If there are <B><I>n</I></B> stocks, you should create <B><I>n</I></B> separate threads. Each thread should be responsible for generating random prices for each stock and writing out the price information about each stock to the appropriate file. Do price generation and file writing for five seconds before exiting the application.</P>
<P>As an “extra credit” exercise, stop an individual thread if the corresponding stock’s price ever reaches its high price range.</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch01/01-01.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch03/03-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 © <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> | <a href="/contactus.html"><font color="#0099CC">Contact Us</font></a> | <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> | <a href="http://www.earthweb.com/dlink.corp|privacy-jhtml.72.0.-.-.jhtml" target="resource window"><font color="#0099CC">Privacy</font></a> | <a href="http://www.itmarketer.com/" target="resource window"><font color="#0099CC">Ad Info</font></a> | <!--<a href="/consortia/"><font color="#0099CC">Consortia</font></a> | --><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 & Conditions</font></a>, <a href="/copyright.html"><font color="#0099CC">Copyright © 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 + -