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

📄 09-03.html

📁 master java threads
💻 HTML
📖 第 1 页 / 共 2 页
字号:
                        <option value="/reference/dir.5-desktoppubanddesign.html">Graphic Design                        <option value="/reference/dir.6-generalinternet.html">General Internet                        <option value="/reference/dir.7-hardwareandos.html">Hardware &amp; OS                        <option value="/reference/dir.8-ibmredbooks.html">IBM RedBooks                        <option value="/reference/dir.9-networktelcom.html">Network &amp; Telecom						<option value="/reference/dir.10-websoftwaredev.html">Web &amp; Software Dev						<option value="/reference/dir.11-careers.html">Careers                        <option value="">-----------                        <option value="/reference/whatsnew.html">New Arrivals                        </SELECT>						</font>			</td>			</tr></table></form>	<!-- LEFT NAV SEARCH END --><table border="0" cellspacing="0" cellpadding="0">	<tr>		<td><a href="/desktop/"><img src="/images/desktop_icona.gif" border=0 alt="Go to ITKnowledge Academic"></a><br><br></td>	</tr></table>		<!-- BEGIN TEXT LINKS --><!-- END TEXT LINKS --><!-- END LEFT NAVBAR --><!-- END LEFT NAVBAR -->		<td width="15"><img src="/images/dotclear.gif" width="15" alt="" border="0"></td><!-- end of ITK left NAV --><!-- begin main content -->		<td width="100%" valign="top" align="left">		<br><!-- END SUB HEADER --><!-- Created by dB Page Builder.  http://www.pchelponline.com/bluestem -->

<!--Begin Content Column -->

<TABLE border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=75 valign=top>
<img src="/images/sm_covers/1562438425.gif" width=60 height=73 alt="Mastering Java Threads" border="1">
</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>&nbsp;1562438425<b>&nbsp;&nbsp;&nbsp;Pub Date:</b>&nbsp;05/01/99</font>&nbsp;&nbsp;<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="">&nbsp;<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="09-02.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-04.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading14"></A><FONT COLOR="#000077">The wait[] &amp; notify[] Methods</FONT></H4>
<P>The methods <B>wait()</B>, <B>notify()</B>, and <B>notifyAll()</B> are used to control synchronization within Java applications. Note that these methods are part of Java&#146;s Object class, not the Thread class.</P>
<P>There are three forms associated with the <B>wait()</B> method, as listed below:</P>
<DL>
<DD><B>1.</B>&nbsp;&nbsp;<SMALL>public final void wait() throws InterruptedException</SMALL>
<DD><B>2.</B>&nbsp;&nbsp;<SMALL>public final void wait(long timeout) throws InterruptedException</SMALL>
<DD><B>3.</B>&nbsp;&nbsp;<SMALL>public final void wait(long timeout, int nanos) throws InterruptedException</SMALL>
</DL>
<P>Note the following points regarding the <B>wait()</B> and <B>notify()</B> methods.</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;The first form of <B>wait()</B> will wait forever; the other two forms will wait for a particular period of time.
<DD><B>&#149;</B>&nbsp;&nbsp;The <B>wait()</B> method will cause a thread to wait until it is notified or the specified timeout expires. It can only be called from within a synchronized method by the thread that holds the lock. The <B>wait()</B> method will also release the monitor.
<TABLE WIDTH="90%">
<TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-04i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">A thread will awaken if the <B>notify()</B> or <B>notifyAll()</B> methods are called.</TD>
</TR>
</TABLE>
<DD><B>&#149;</B>&nbsp;&nbsp;The <B>notify()</B> method notifies a single waiting thread of a change in condition of another thread. The thread effecting the change notifies the waiting thread using <B>notify()</B>. Threads that want to wait for a condition to change before proceeding can call <B>wait()</B>.
<DD><B>&#149;</B>&nbsp;&nbsp;The <B>notifyAll()</B> method notifies <I>all</I> threads waiting for a condition to change. Threads that are waiting are generally waiting for another thread to change some condition. Thus, the thread effecting a change for which more than one thread is waiting notifies all of the waiting threads using the method <B>notifyAll()</B>. One of the waiting threads will grab the monitor and proceed. The other waiting threads will be forced to wait longer.
<DD><B>&#149;</B>&nbsp;&nbsp;The <B>notify()</B> and <B>notifyAll()</B> methods can only be called from within a synchronized method by the thread that holds the lock.
<TABLE WIDTH="90%">
<TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-05i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">Most often, you should use <B>notifyAll()</B> over the <B>notify()</B> method.</TD>
</TR>
</TABLE>
</DL>
<P><FONT SIZE="+1"><B>Producer &amp; Consumer Interaction</B></FONT></P>
<P>Table 9-1 implements a timeline so the interaction between the Producer and Consumer with the monitor can be seen.
</P>
<TABLE WIDTH="100%" BORDER><TR>
<CAPTION ALIGN="CENTER" VALIGN="BOTTOM"><B>Table 9-1: Interaction of the Producer and the Consumer with the monitor</B></CAPTION>
</TR>
<TR>
<TH ALIGN="CENTER" VALIGN="TOP" WIDTH="20%">Time</TH>
<TH ALIGN="CENTER" VALIGN="TOP" WIDTH="40%">Consumer</TH>
<TH ALIGN="CENTER" VALIGN="TOP" WIDTH="40%">Producer</TH>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T1</TD>
<TD ALIGN="LEFT" VALIGN="TOP"><B>Run()</B> calls <B>get()</B> and the Consumer acquires the monitor when it enters <B>Get()</B>.</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Polling thread pulls some stock info off of the server.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T2</TD>
<TD ALIGN="LEFT" VALIGN="TOP">&nbsp;</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Thread calls <B>put()</B>, but because the Consumer has the monitor, the Producer is forced to sleep at the entrance to <B>put()</B>.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T3</TD>
<TD ALIGN="LEFT" VALIGN="TOP">No stock available, so calls <B>wait()</B>. which releases the monitor</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Locked out...</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T4</TD>
<TD ALIGN="LEFT" VALIGN="TOP">waiting...</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Wakes up and enters <B>put()</B>. The Producer now has the monitor.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T5</TD>
<TD ALIGN="LEFT" VALIGN="TOP">waiting...</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Puts stock information into a Stock object.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T6</TD>
<TD ALIGN="LEFT" VALIGN="TOP">waiting...</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Sets <SMALL>m_bStockPending</SMALL> to true</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T7</TD>
<TD ALIGN="LEFT" VALIGN="TOP">waiting...</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Calls <B>notifyAll()</B></TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T8</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Woken and waiting for its time slice</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Exits <B>put()</B> and releases the monitor</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T9</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Gets out of the while loop. Reacquires the monitor.</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Polls for another stock. it is locked out of <B>put()</B> until the Consumer finishes.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T10</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Fetches the stock object and inserts it into the database.</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Gets another stock and calls <B>put()</B>.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T11</TD>
<TD ALIGN="LEFT" VALIGN="TOP">&nbsp;</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Locked out of put until the monitor is released</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T12</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Calls <B>notifyAll()</B> and exits <B>get()</B>. The monitor is released.</TD>
<TD ALIGN="LEFT" VALIGN="TOP">&nbsp;</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T13</TD>
<TD ALIGN="LEFT" VALIGN="TOP">&nbsp;</TD>
<TD ALIGN="LEFT" VALIGN="TOP">Enters <B>put()</B> and acquires the monitor.</TD>
</TR>
<TR>
<TD ALIGN="CENTER" VALIGN="TOP">T14</TD>
<TD ALIGN="LEFT" VALIGN="TOP"><B>Run()</B> calls <B>get()</B>, but the Consumer is locked out.</TD>
<TD ALIGN="LEFT" VALIGN="TOP">&nbsp;</TD>
</TR>
</TABLE>
<H3><A NAME="Heading15"></A><FONT COLOR="#000077">Another Example of Synchronization</FONT></H3>
<P>The following example is by Chuck McManis, as published in <I>Java World Magazine</I><SUP><SMALL><B>1</B></SMALL></SUP>. It is a simple simulation of a ping pong game involving two players, Bob and Alice. The shared resource is a ping pong table, which is represented by the Java object named <SMALL>PingPong</SMALL>.</P>

<BLOCKQUOTE>
<HR>
<SUP><SMALL><B>1</B></SMALL></SUP><FONT SIZE="-1">April 1996 issue.
</FONT>
<HR>
</BLOCKQUOTE>

<H4 ALIGN="LEFT"><A NAME="Heading16"></A><FONT COLOR="#000077">How the Program Starts</FONT></H4>
<P>The program starts off by creating a <SMALL>PingPong</SMALL> object, and then creates two players, each of which plays the game in a separate thread. After sleeping for 5 seconds, the game is terminated.</P>
<P>The <SMALL>Player</SMALL> object consists of a pointer to the <SMALL>PingPong</SMALL> table object and the name of the player&#146;s opponent. The Player&#146;s <B>run()</B> method loops continuously, calling <B>PingPong.hit()</B> until the PingPong&#146;s hit method returns <B>false</B>.</P>
<H4 ALIGN="LEFT"><A NAME="Heading17"></A><FONT COLOR="#000077">Guts of the Program</FONT></H4>
<P>The real guts of the program are in the <B>PingPong</B> method. You can consider the &#147;ball&#148; as being the critical shared resource; only one player can hit the ball at a time. The action of hitting the &#147;ball&#148; is represented by the following statement:</P>
<!-- CODE SNIP //-->
<PRE>
         System.out.println(&#147;PING! (&#147;&#43;x&#43;&#148;) &#148;);
</PRE>
<!-- END CODE SNIP //-->
<P>Only one player can reach this code at a time. More importantly, a thread cannot execute this statement twice in a row; this statement must be executed alternatively by thread one and thread two.
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="09-02.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-04.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 + -