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

📄 01-01.html

📁 master java threads
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<P>There is a problem with single tasking, however: if a certain task is slow or blocking, it can slow or halt the entire execution of a program. Consider code that implements an input monitor for a user-interface library and blocks until the user types a character, as shown below.
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
main(int argc, char **argv)

{

  int c;

  while (1)

  {

    c = getchar();

    if (c == ESC)

      break;

    ProcessKeyboardInput (c);

    ProcessMouseInput();

  }

  exit (0);
}
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>

<P><FONT SIZE="+1"><B>Other Examples</B></FONT></P>
<P>Another example of a single-tasking application is a spreadsheet that performs automatic recalculation. The recalculation process may suspend user interaction (with the spreadsheet file or the entire operating system) until the recalculation is complete.
</P>
<P>How can this undesirable situation be alleviated? How can you write an application that allows for particular application events to occur while not freezing the user&#146;s system?</P>
<H4 ALIGN="LEFT"><A NAME="Heading4"></A><FONT COLOR="#000077">&#147;Simulated&#148; Multitasking</FONT></H4>
<P>Back in the &#147;good old days&#148; of programming, application developers utilized a variety of techniques to simulate multitasking in order to avoid blocking waits.
</P>
<P>Among the techniques used to avoid blocking program waits were:</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;Event loops
<DD><B>&#149;</B>&nbsp;&nbsp;the <B>select()</B> function
<DD><B>&#149;</B>&nbsp;&nbsp;timeouts (using alarms)
<DD><B>&#149;</B>&nbsp;&nbsp;context swapping
</DL>
<P>Writing your own multitasking system can be 1) tedious and time-consuming (making it uneconomical) and 2) nonportable to other operating systems. Solutions have traditionally been proprietary in nature.
</P>
<P>What is necessary and practical is a method of implementing multitasking within an application that is:</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;portable
<DD><B>&#149;</B>&nbsp;&nbsp;standardized
</DL>
<H4 ALIGN="LEFT"><A NAME="Heading5"></A><FONT COLOR="#000077">Lightweight Processes &amp; Threads</FONT></H4>
<P>UNIX and other operating systems have pioneered the concept of <I>lightweight processes</I>. Lightweight processes are more commonly called <I>threads</I>.</P>
<TABLE WIDTH="90%"><TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/01-01i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT"><B>Thread:</B> also known as a lightweight process, this is a single sequential flow of control within an application or applet process.</TD>
</TR>
</TABLE>
<P>Multithreaded programs typically perform different tasks simultaneously. This creates the illusion of different parts of an application executing simultaneously on different computers or processors.
</P>
<H3><A NAME="Heading6"></A><FONT COLOR="#000077">Threads &amp; Data Space</FONT></H3>
<P>A system that has a single task with multiple threads is different than a true multitasking system.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading7"></A><FONT COLOR="#000077">What Tasks Contain</FONT></H4>
<P>Each task in a multitasking system contains:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;its own data space
<DD><B>&#149;</B>&nbsp;&nbsp;its own register set
</DL>
<TABLE WIDTH="90%">
<TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/01-02i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT">Process switches are slow and expensive.</TD>
</TR>
</TABLE>
<H4 ALIGN="LEFT"><A NAME="Heading8"></A><FONT COLOR="#000077">Thread Characteristics</FONT></H4>
<P>In a multithreaded system, each thread:
</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;shares the same global data space
<DD><B>&#149;</B>&nbsp;&nbsp;can access the same exact variable in heap memory
<DD><B>&#149;</B>&nbsp;&nbsp;can have private data variables that are allocated on the stack
</DL>
<P><FONT SIZE="+1"><B>Decreased Overhead</B></FONT></P>
<P>In a multithreaded application, each thread runs within the same process space; thus, the overhead of switching between different <I>threads</I> is much less than the overhead of switching between different <I>processes</I> in a multitasking system.</P>
<P>One beneficial aspect of threads is that it is easy for different threads to share global data. In a true multitasking system, it is usually tedious to share data between different processes.</P>
<TABLE WIDTH="90%"><TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/01-03i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT">A system that has a single task with multiple threads is different than a true multitasking system.</TD>
</TR>
</TABLE>
<H3><A NAME="Heading9"></A><FONT COLOR="#000077">Concurrent Execution</FONT></H3>
<P>Each thread in an application can run concurrently. A program typically has a single thread of execution. As the program runs, you can create more threads, as needed. Each thread is typically used to carry out some type of background task.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading10"></A><FONT COLOR="#000077">An Example</FONT></H4>
<P>For example, in the spreadsheet example used earlier, a separate thread could be created which performs recalculations in the background. Another thread could be used to wait for user input.
</P>
<P>The following characteristics apply to threads:</P>
<DL>
<DD><B>&#149;</B>&nbsp;&nbsp;A thread can run continuously in a loop for the entire duration of the program (for example, a thread can continually poll the mouse for movements and button clicks).
<DD><B>&#149;</B>&nbsp;&nbsp;Alternately, a thread can contain a single set of instructions that is executed just once before the thread terminates (such as a one-time spreadsheet recalculation).
</DL>
<TABLE WIDTH="90%">
<TR>
<TD VALIGN="TOP" WIDTH="5%" ALIGN="LEFT"><IMG SRC="images/01-04i.jpg"></TD>
<TD VALIGN="TOP" ALIGN="LEFT">A Java program will run until all nondaemon threads have been terminated.</TD>
</TR>
</TABLE>
<H3><A NAME="Heading11"></A><FONT COLOR="#000077">Writing Threaded Java Apps</FONT></H3>
<H4 ALIGN="LEFT"><A NAME="Heading12"></A><FONT COLOR="#000077">Exercise 1-1: Writing your first threaded Java application</FONT></H4>
<P>The first threaded Java application you will write is a simple counter. This app will count from 1 to 10 and then exit. This file will be a simple console application, run by the stand-alone Java interpreter. Name the file <SMALL>COUNTER1.JAVA</SMALL>, copying the code shown below.</P>

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

{

  public static void main(String args[])

  {

   Counter1Thread t = new Counter1Thread();

   t.start();

   System.out.println(&#147;main() has finished.&#148;);
 }

}


class Counter1Thread extends Thread

{

  Counter1Thread()

  {

  }


  public void run()

  {

   for (int i = 1; i &lt;= 10; i&#43;&#43;)

   {

      System.out.println(&#147;i is &#148; &#43; i);

    {

   System.out.println(&#147;The thread is finished&#148;);

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

<P>The output from the <SMALL>COUNTER1.JAVA</SMALL> program is as follows:</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
main () has finished.

i is 1

i is 2

i is 3

i is 4

i is 5

i is 6

i is 7

i is 8

i is 9

i is 10

The thread is finished
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>

<H4 ALIGN="LEFT"><A NAME="Heading13"></A><FONT COLOR="#000077">Exercise 1-2: Writing a Java app with two threads</FONT></H4>
<P>As a variation on the first application, the following exercise adds another thread. Each thread in the application will count from 1 to 10 and then exit. Name this app <SMALL>COUNTER2.JAVA</SMALL>.</P>

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

{

  public static void main(String args[])

  {

    Counter2Thread t1 = new Counter2Thread (&#147;First Thread&#148;);

    Counter2Thread t2 = new Counter2Thread (&#147;Second Thread&#148;);

    t1.start();

    t2.start();

    System.out.println(&#147;main() has finished.&#148;);

  }

}


class Counter2Thread extends Thread

{

   Counter2Thread(String szName)

   {

     super (szName);

   }


   public void run()

   {

     for (int i = 1; i &lt;= 10; i&#43;&#43;)

   {

      System.out.println(getName() &#43; &#147;:\ti is &#148; &#43; i);

   }

   System.out.println(getName() &#43; &#147; is finished&#148;);

  }

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

<P>The output from this program is as follows:
</P>

<TABLE BORDER="2" BORDERCOLOR="#0000" ALIGN="CENTER">
<TR><TD>
<!-- CODE //-->
<PRE>
main () has finished.

First Thread:  i is 1

First Thread:  i is 2

First Thread:  i is 3

First Thread:  i is 4

First Thread:  i is 5

First Thread:  i is 6

First Thread:  i is 7

First Thread:  i is 8

First Thread:  i is 9

First Thread:  i is 10

Second Thread: i is 1

Second Thread: i is 2

Second Thread: i is 3

Second Thread: i is 4

Second Thread: i is 5

Second Thread: i is 6

Second Thread: i is 7

Second Thread: i is 8

Second Thread: i is 9

Second Thread: i is 10

Second Thread is finished

First Thread is finished
</PRE>
<!-- END CODE //-->
</TD>
</TR>
</TABLE>

<P><FONT SIZE="+1"><B>Starvation</B></FONT></P>
<P>This Java application illustrates one of the interesting problems with multiple threads&#151;<I>starvation</I>. The subject of starvation will be discussed later in this course.</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="../intro.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch02/02-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 &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 + -