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

📄 09-04.html

📁 master java threads
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<PRE>
public class Game

{

   public static void main(String args[])

   {

      PingPong table = new PingPong();

      Thread alice = new Thread(new Player(&#147;bob&#148;, table));

      Thread bob = new Thread(new Player(&#147;alice&#148;, table));


      alice.setName(&#147;alice&3148;);

      bob.setName(&#147;bob&3148;);

      alice. start(); // alice starts playing

      bob.start(); // bob starts playing


      try

      {

         // Wait 5 seconds

         Thread.currentThread().sleep(5000);

      }

      catch (InterruptedException e)

      {

      }


      table.hit(&#147;DONE&3148;); // cause the players to quit their
threads.

      try

      {

         Thread.currentThread().sleep(100);

      }

      catch (InterruptedException e)

      {

      }

   }

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

<P><SMALL><B>PLAYER.JAVA</B></SMALL></P>

<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
public class Player implements Runnable

{

    PingPong myTable;   // Table where they play

    String myOpponent;


    public Player(String opponent, PingPong table)

   {

      myTable   = table;

      myOpponent = opponent;

   }

   public void run()

   {

     while (myTable.hit(myOpponent))

       ;

   }

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

<P><SMALL><B>PINGPONG.JAVA</B></SMALL></P>

<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
public class PingPong

{

    // state variable identifying whose turn it is.

    private String whoseTurn = null;


    public synchronized boolean hit(String opponent)

   {

      String x = Thread.currentThread().getName();


     if (whoseTurn == null)

     {

        whoseTurn = x;

        return true;

     }


     if (whoseTurn.compareTo (&#147;DONE&#148;) == 0)

       return false;


     if (opponent.compareTo (&#147;DONE&#148;) == 0)

     {

       whoseTurn = opponent;

       notifyAll();

       return false;

     }


     if (x.compareTo (whoseTurn) == 0)

     {

       System.out.println(&#147;PING! (&#147;&#43;x&#43;&#148;) &#148;);

       whoseTurn = opponent;

       notifyAll();

     }

     else

     {

      try

      {

        long t1 = System.currentTimeMillis();

        wait (2500);

        if ((System.currentTimeMillis() - t1) &gt; 2500)

        {

          System.out.println(

            &#147;****** TIMEOUT! &#148; &#43; x &#43;

            &#147; is waiting for &#147;&#43;whoseTurn&#43;&#148; to play.&#148;);

        }

      }

      catch (InterruptedException e)

     {

     }

   }

   return true; // keep playing.

  }

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

<H3><A NAME="Heading18"></A><FONT COLOR="#000077">Deadlock</FONT></H3>
<P>Deadlock is a situation in which multiple threads are waiting on multiple locks to be freed, but those locks will never be (or are never) freed. Below is a simplistic example of deadlock.
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" WIDTH="90%" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
public void father()

{
    synchronized(respect)

   {

     respect.get();

     synchronized (allowance)

     {

        allowance.give();

     }

   }

}

public void son()

{

    synchronized(allowance)

   {

      allowance.get();

      synchronized(respect)

     {

        respect.give();

     }

   }

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

<H4 ALIGN="LEFT"><A NAME="Heading19"></A><FONT COLOR="#000077">Example Analysis</FONT></H4>
<P>Once the <SMALL>father</SMALL> object gets respect, he will lock the <SMALL>allowance</SMALL> object, deposit some money into it, and then release it. However, the only way that the <SMALL>son</SMALL> object will unlock the <SMALL>respect</SMALL> object is if he gets the <SMALL>allowance</SMALL> object. In this example, you can see that the <SMALL>father</SMALL> and <SMALL>son</SMALL> objects have locks on objects that the other needs in order to proceed. The application will be in a deadly, infinite embrace waiting for the locks to be freed.</P>
<TABLE WIDTH="90%"><TR>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="5%"><IMG SRC="images/09-06i.jpg"></TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="85%">This is the classic &#147;which came first, the chicken or the egg?&#148; scenario.</TD>
</TR>
</TABLE>
<H4 ALIGN="LEFT"><A NAME="Heading20"></A><FONT COLOR="#000077">Difficult to Detect</FONT></H4>
<P>Deadlock is very difficult to detect. Java does not contain any type of automated functions to detect deadlock, nor does Java contain any kind of run-time deadlock detection.
</P>
<P>There are two ways to avoid deadlock:</P>
<DL>
<DD><B>1.</B>&nbsp;&nbsp;<U>One synchronized method should never call another synchronized method</U>. This rule is often impractical in the real world. Java contains synchronized methods (such as <B>Vector.addElement()</B>) that you will call from your own synchronized methods.
<DD><B>2.</B>&nbsp;&nbsp;<U>Use some sort of higher-level object to be locked</U>. For example, you might have a <SMALL>Family</SMALL> object declared as follows:
</DL>

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

{


      public synchronized father();

      public synchronized son();


...

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

<P>The problem with the above example is that the locking granularity might be too large. For example, with the class above, the other sons and daughters might not be able to get their allowance until the obstinate son relinquishes and gives respect to the father.
</P>
<P>The best way to avoid deadlock is to ensure that locks are always acquired in the same order. In the previous example, the lock for the <SMALL>respect</SMALL> object would be acquired before the lock for the <SMALL>allowance</SMALL> object.</P>
<P><B>Lab 4: Bringing It All Together&#151;A Final Exercise</B></P>
<P>In the preceding Lesson, you learned about synchronization issues and how to share a single resource among multiple threads.</P>
<P>In this Lab, write a Java program to simulate the following (albeit unrealistic) scenario:</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;you live in a city that has 5 telephones but only one &#147;connection.&#148;
<DD><B>&#149;</B>&nbsp;&nbsp;You can divide the 5 phones into 3 callers and 2 receivers.
<DD><B>&#149;</B>&nbsp;&nbsp;A caller can only connect to a receiver.
<DD><B>&#149;</B>&nbsp;&nbsp;When a caller dials a number, there might be another party using the line. Therefore, the caller and the corresponding receiver must wait until the connection becomes free before they can communicate with each other.
<DD><B>&#149;</B>&nbsp;&nbsp;When two parties finally do connect with each other, all other callers and receivers are locked out of the connection until the conversation is finished.
</DL>
<P>There are many ways to model this Java problem; feel free to express your creativity. There is no right or wrong way of approaching this programming challenge. You should use everything you have learned in this course to create this application. If necessary, review various sections of this course.
</P>
<P>As an additional exercise, you can generalize your solution so that it will work if you decide to add <B><I>n</I></B> connections to your surrealistic phone network.</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="09-03.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ewtoc.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 + -