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

📄 09-01.html

📁 master java threads
💻 HTML
📖 第 1 页 / 共 2 页
字号:
    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="../ch08/08-03.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-02.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H2><A NAME="Heading1"></A><FONT COLOR="#000077">Chapter 9<BR>Synchronization
</FONT></H2>
<P><BIG><B>Lesson Topics</B></BIG></P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;Synchronization: An Introduction
<DD><B>&#149;</B>&nbsp;&nbsp;Monitors
<DD><B>&#149;</B>&nbsp;&nbsp;The Scope of a Lock
<DD><B>&#149;</B>&nbsp;&nbsp;Synchronized Blocks
<DD><B>&#149;</B>&nbsp;&nbsp;Another Example of Synchronization
<DD><B>&#149;</B>&nbsp;&nbsp;Deadlock
</DL>
<H3><A NAME="Heading2"></A><FONT COLOR="#000077">Synchronization: An Introduction</FONT></H3>
<P>Threads have their own stack space and their locally declared variables are private to the thread that created them. However, threads can also access global variables that are stored on the global heap. For example, consider the following (incomplete) applet that retrieves stock prices from an Internet server:
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
import java.applet.*;


class StockApp extends Applet implements Runnable

{

  public String m_szStockName;

  public double m_dblStockPrice;

  public boolean m_bStockPending = false;


  public PollingThread m_ReutersPollingThread =

      new PollingThread(&#147;Reuters&#148;);

  public PollingThread m_TeleratePollingThread =

      new PollingThread(&#147;Telerate&#148;);


  public void start()

  {

    m_ReutersPollingThread.start();

    m_TeleratePollingThread.start();

  }


  public void run()

  {

     while (m_ReutersPollingThread null &amp;&amp;

            m_TeleratePollingThread != null)

     {

       if (m_bStockPending == true)

       {

          ProcessPendingStock();

       }

       try

       {

          Thread.sleep(1000);

       } catch (InterruptedException e)

     }

  }

  public void ProcessPendingStock()

  {

     /*

        Insert the stock info into a database. . . .

     */


     m_bStockPending = false;

  }


  class PollingThread extends Thread

  {

    public PollingThread(String szName)

    {

       super(szName);


       /*

  We can open a server connection based on the thread name

       */

     }


     public void run()

     {

     for (;;)

     {

        /*

           Read the stock info from the server. . . .

           We block until we get a stock.

        */

        try

        {

           Thread.sleep(1000);

         } catch (InterruptedException e)

         {

         }


         /*

         if (we got a response from the server)

         {

         */

            m_szStockName = &#147;MSFT&#148;;

            m_dblStockPrice = 120.50;

            m_bStockPending = true;

         /*

         }

         */

       }

     }

   }

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

<H4 ALIGN="LEFT"><A NAME="Heading3"></A><FONT COLOR="#000077">Global Variables</FONT></H4>
<P>This applet has three global variables that relate to stock prices:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;<SMALL>public String m_szStockName;</SMALL>
<DD><B>&#149;</B>&nbsp;&nbsp;<SMALL>public double m_dblStockPrice;</SMALL>
<DD><B>&#149;</B>&nbsp;&nbsp;<SMALL>public boolean m_bStockPending = false;</SMALL>
</DL>
<P>The variable <SMALL>m_bStockPending</SMALL> is set to <B>true</B> by one of the server-polling threads when new stock information is retrieved from the server. The thread also sets the two variables that record the stock&#146;s symbol and price.</P>
<P>When the main thread sees that the value of <SMALL>m_bStockPending</SMALL> changes to <B>true</B>, it realizes that there is new stock information which it must insert into some database. It places the values in the database and resets the <SMALL>m_bStockpending</SMALL> variable back to <B>false</B>. It then continues to loop, waiting for a new stock record to appear.</P>
<P><FONT SIZE="+1"><B>Problems</B></FONT></P>
<P>There are several problems with the previous example:
</P>
<DL>
<DD><B>1.</B>&nbsp;&nbsp;<B>Q:</B> what happens if the Reuters thread receives information about a stock, but before the main thread can act upon it, another stock record comes in from Reuters? <B>A:</B> the information regarding the second stock would overwrite that regarding the first stock.
<DD><B>2.</B>&nbsp;&nbsp;<B>Q:</B> what happens if stock information then comes from the Telerate server for a third stock? <B>A:</B> if the main thread has not yet processed the information from Reuters, the information on this third stock will overwrite the information for the second stock.
</DL>
<P>You can theoretically have the following situation:
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
Time       Reuters         Telerate

T&#43;0        m_szStockName = &#147;MSFT&#148;

T&#43;1        m_szStockName = &#147;DELL&3148;

T&#43;2        m_dblStockPrice = 77.375

T&#43;3        m_dblStockPrice = 120
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>

<P>As you can see, the stock information shows DELL stock with a price of 120.375 per share, which is incorrect.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading4"></A><FONT COLOR="#000077">Atomic Operations</FONT></H4>
<P>What is preferable in the previous example is to have the operation on the stock be <I>atomic</I>. When an operation or a function is considered to be <I>atomic</I>, it is considered to be uninterruptable during its execution.</P>
<P>The problem with this example is that access to the global variables is not <I>synchronized</I> between the three threads that are running in the application.</P>
<TABLE WIDTH="90%"><TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-01i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">If multiple threads are competing for the use of a shared resource, the access to this resource should be synchronized.</TD>
</TR>
</TABLE>
<H4 ALIGN="LEFT"><A NAME="Heading5"></A><FONT COLOR="#000077">Producer/Consumer Scenarios</FONT></H4>
<P>The above code illustrates a typical <I>Producer/Consumer</I> scenario. In this type of scenario, one thread produces data while another thread consumes the data.</P>
<P><FONT SIZE="+1"><B>Producer Thread</B></FONT></P>
<P>In a User Interface system, one thread might gather mouse events&#151;mouse movements, button presses, and button releases. As the mouse events are gathered, they are placed at the tail of a system queue that is used to monitor user interface events. This is an example of a Producer thread&#151;it produces events.
</P>
<P><FONT SIZE="+1"><B>Consumer Thread</B></FONT></P>
<P>While the User Interface threads are placing data into the system queue, another process is removing events from the head of the queue. This is an example of a Consumer thread&#151;it &#147;eats&#148; data generated by the Producer thread.
</P>
<P>Both threads&#151;the producer and the consumer&#151;have to manipulate the system queue. The Producer changes the head and tail pointers of the queue when it <I>inserts</I> data. The Consumer manipulates these pointers when it <I>removes</I> data from the queue.</P>
<P><FONT SIZE="+1"><B>Synchronizing the Queue</B></FONT></P>
<P>The queue is a valuable system resource whose access must be synchronized. If access is not synchronized to the queue, one thread can be manipulating the head pointer while another thread is manipulating the tail pointer.
</P>
<H3><A NAME="Heading6"></A><FONT COLOR="#000077">Monitors</FONT></H3>
<P>A <I>monitor</I> is a synchronization mechanism that has been in use for many years in the world of concurrent programming. A monitor is also known as a <I>mutex lock</I>. A monitor is associated with a specific variable and serves as a lock/release mechanism on that variable.</P>
<P>For example, in the StockApp program created previously in this course, you can place a monitor on the <SMALL>m_bStockPending</SMALL> variable that prohibits more than one thread from accessing the global variables at one time.</P>
<P>Note the following points regarding monitors:</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;Only one thread at a time is allowed to grab a lock.
<DD><B>&#149;</B>&nbsp;&nbsp;It is not possible for two threads to hold a lock on an object.
</DL>
<P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../ch08/08-03.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-02.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 + -