09-02.html

来自「master java threads」· HTML 代码 · 共 752 行 · 第 1/2 页

HTML
752
字号
<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-01.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-03.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading7"></A><FONT COLOR="#000077">Critical Sections</FONT></H4>
<P>A section of code to which only one thread is allowed access is called a <I>critical section</I>. True multiprocessing systems recognize the need for critical sections and implement them within the operating system. For example, the Win32 API has the <SMALL>EnterCriticalSection</SMALL> and <SMALL>LeaveCriticalSection</SMALL> functions which allow you to surround code that is intended for access by one thread at a time.</P>
<H4 ALIGN="LEFT"><A NAME="Heading8"></A><FONT COLOR="#000077">Synchronized</FONT></H4>
<P>Java implements critical sections through the use of the keyword <B>synchronized</B>. You can mark any block of code as being a synchronized block, although this keyword is generally used to mark an entire method within a class.</P>
<P>Below is the StockApp rewritten to take advantage of monitors:</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)

    {

      ProcessPendingStock();

    }

  }


  public <B>synchronized</B> void InsertPendingStock (

           String sStockName, double dblPrice)

  {

     while (m_bStockPending == true)

     {

     <B>try</B>

     <B>{</B>

        <B>wait();</B>

     <B>} catch (InterruptedException e)</B>

     <B>{</B>

     <B>}</B>

   }



    m_szStockName = sStockName;

    m_dblStockPrice = dblPrice;

    m_bStockPending = false;

    <B>notifyAll();</B>

  }


  public <B>synchronized</B> void ProcessPendingStock ()

  {

    /*

       Insert the stock info into a database. . . .

    */


    while (m_bStockPending == false)

    {

      <B>try</B>

      <B>{</B>

         <B>wait();</B>

      <B>} catch (InterruptedException e)</B>

      <B>{</B>

      <B>}</B>

    }


    m_bStockPending = false;

    <B>notifyAll();</B>

  }



  class PollingThread extends Thread

  {

     public PollingThread (String szName)

     {

       super(szName);


       /*

         We can open a server connection based on the thread name

       */

    }


    public void run()

    {

      String sStockName;

      double dblPrice;


      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)

        {

           read the stock name/price into local variables

           sStockName and dblPrice

        */

           InsertPendingStock(sStockName, dblPrice);

         /*

         }

         */

       }

     }

  }

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

<H3><A NAME="Heading9"></A><FONT COLOR="#000077">The Scope of a Lock</FONT></H3>
<P>The <I>scope of a lock</I> is the period of time between when a lock is acquired and when it is released. If an entire method is synchronized, the lock is said to have <I>method scope</I>.</P>
<P>Note the following points regarding the scope of a lock.</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;Try to keep the scope of a lock as short as possible.
<DD><B>&#149;</B>&nbsp;&nbsp;Do not keep other threads locked out of code for long periods of time.
</DL>
<H4 ALIGN="LEFT"><A NAME="Heading10"></A><FONT COLOR="#000077">Object &amp; Class Locks</FONT></H4>
<P>Each instance of an Object in Java has a lock associated with it. When an Object is created, the lock is disabled. The <B>synchronized</B> keyword is used to define the scope when the lock on an object will be enabled.</P>
<P>When an entire method is synchronized, the Object with which the method is associated is locked for the scope of that method. For instance, in the example in the previous section, the instance of the StockApp object is locked when <B>ProcessPendingStock()</B> is called.</P>
<P>A lock is associated with an <B>instance</B> of an Object. Thus, if you have two separate instances of an Object, your application can execute a synchronized method multiple times simultaneously, once for each instance.</P>
<P><FONT SIZE="+1"><B>Class Locks</B></FONT></P>
<P>What happens if a <B>static</B> method is synchronized? As you should know, in Java there is no instance of an Object that is associated with a static method. Thus, there is no instance of an Object to lock. In this case, Java locks something that is referred to as a <I>class lock</I>. Internally, the class lock is really the lock on the Java Object which is used to represent the class itself.</P>
<P>A class lock is distinct from the object lock. You can hold and release a lock on the class independently from the lock on an object.</P>
<TABLE WIDTH="90%"><TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-02i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">If an entire method is synchronized, the lock is said to have <I>method scope</I>.</TD>
</TR>
</TABLE>
<H3><A NAME="Heading11"></A><FONT COLOR="#000077">Synchronized Blocks</FONT></H3>
<P>The <B>synchronized</B> keyword cannot only be used to modify an entire method, but it can also be used to enclose a block of code within a non-synchronized method. The syntax of a synchronized block is as follows:</P>
<!-- CODE SNIP //-->
<PRE>
    <B>synchronized</B> <I>(  Expression ) Block</I>
</PRE>
<!-- END CODE SNIP //-->
<P>If the type of <I>Expression</I> is not a reference to an Object, a compile-time error will occur. For example, it <I>cannot</I> be an expression such as the following:</P>
<!-- CODE SNIP //-->
<PRE>
    synchronized (1&#43;2)
</PRE>
<!-- END CODE SNIP //-->
<H4 ALIGN="LEFT"><A NAME="Heading12"></A><FONT COLOR="#000077">Block Execution</FONT></H4>
<P>You should allow the non-null value of the <I>Expression</I> be <I>V</I>. The executing thread locks the lock associated with <I>V</I>. Then the <I>Block</I> is executed. If execution of the <I>Block</I> completes normally, the lock is unlocked and the synchronized statement completes normally. If execution of the <I>Block</I> completes abruptly for any reason, the lock is unlocked and the synchronized statement then completes abruptly for the same reason.</P>
<P>Acquiring the lock associated with an object does not in itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.</P>
<H4 ALIGN="LEFT"><A NAME="Heading13"></A><FONT COLOR="#000077">Synchronized Blocks vs Methods</FONT></H4>
<P>Which kind of locking method should you use? Synchronizing 1) a block or 2) an entire method? Other than the issues listed below, personal preference dictates which variant of locking to use.
</P>
<P><FONT SIZE="+1"><B>Pros &amp; Cons</B></FONT></P>
<P>Synchronizing a method offers pros and cons:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;<B>Pro:</B> is easy to use
<DD><B>&#149;</B>&nbsp;&nbsp;<B>Con:</B> may result in a lock scope that is too large
<TABLE WIDTH="90%">
<TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-03i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">Synchronizing a block may be expensive if you acquire and release a lock, only to reacquire and re-release it a few lines later. Locks are expensive to obtain and release.</TD>
</TR>
</TABLE>
</DL>
<P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="09-01.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="09-03.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 + =
减小字号Ctrl + -
显示快捷键?