📄 358-363.html
字号:
<HTML>
<HEAD>
<META name=vsisbn content="1571690433"><META name=vstitle content="Black Art of Java Game Programming"><META name=vsauthor content="Joel Fan"><META name=vsimprint content="Sams"><META name=vspublisher content="Macmillan Computer Publishing"><META name=vspubdate content="11/01/96"><META name=vscategory content="Web and Software Development: Programming, Scripting, and Markup Languages: Java"><TITLE>Black Art of Java Game Programming:Advanced Techniques</TITLE>
<!-- HEADER --><STYLE type="text/css"> <!-- A:hover { color : Red; } --></STYLE><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><script><!--function displayWindow(url, width, height) { var Win = window.open(url,"displayWindow",'width=' + width +',height=' + height + ',resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></script><SCRIPT><!--function popUp(url) { var Win = window.open(url,"displayWindow",'width=400,height=300,resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></SCRIPT><script language="JavaScript1.2"><!--function checkForQuery(fm) { /* get the query value */ var i = escape(fm.query.value); if (i == "") { alert('Please enter a search word or phrase'); return false; } /* query is blank, dont run the .jsp file */ else return true; /* execute the .jsp file */}//--></script></HEAD><BODY>
<TABLE border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=75 valign=top>
<img src="../1571690433.gif" width=60 height=73 alt="Black Art of Java Game Programming" border="1">
</td>
<td align="left">
<font face="arial, helvetica" size="-1" color="#336633"><b>Black Art of Java Game Programming</b></font>
<br>
<font face="arial, helvetica" size="-1"><i>by Joel Fan</i>
<br>
Sams, Macmillan Computer Publishing
<br>
<b>ISBN:</b> 1571690433<b> Pub Date:</b> 11/01/96</font>
</td>
</tr>
</table>
<P>
<!--ISBN=1571690433//-->
<!--TITLE=Black Art of Java Game Programming//-->
<!--AUTHOR=Joel Fan//-->
<!--AUTHOR=Eric Ries//-->
<!--AUTHOR=Calin Tenitchi//-->
<!--PUBLISHER=Macmillan Computer Publishing//-->
<!--IMPRINT=Sams//-->
<!--CHAPTER=10//-->
<!--PAGES=358-363//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="353-358.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="363-368.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading7"></A><FONT COLOR="#000077">A Quick Review of Threads</FONT></H4>
<P>As we learned in Chapter 8, a thread is a mini-program that runs independently. You can have several threads of execution in a Java application or applet; in fact, the number of threads is limited only by system resources. Threads are useful whenever you need to perform multiple concurrent actions that are inconvenient or impossible to synchronize. The classic example is that of a server process, such as a World Wide Web server, which needs to handle several clients at once.
</P>
<P>The Web server talks to each of the connected clients, and at the same time, listens for new requests. With threads, this is easily accomplished. A single thread waits for requests from clients. As each request comes in, a new thread is spawned to communicate with each client. When the conversation is over, the thread disappears. Figure 10-1 shows this sequence of events.</P>
<P><A NAME="Fig1"></A><A HREF="javascript:displayWindow('images/10-01.jpg',600,409 )"><IMG SRC="images/10-01t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/10-01.jpg',600,409)"><FONT COLOR="#000077"><B>Figure 10-1</B></FONT></A> Threads in a Web server</P>
<P>Here’s another example. Most games need to track the progress of several independent objects through time, such as a player and his opponents. You can create a separate thread to handle each game object. Interactions in the game world are modeled by communication between the separate threads. You’ll see how to structure games in this manner really soon!
</P>
<P>Now, let’s see how to create threads.</P>
<H4 ALIGN="LEFT"><A NAME="Heading8"></A><FONT COLOR="#000077">Creating Threads</FONT></H4>
<P>The java.lang.Thread class is the base class for all thread objects. To create a separate thread of execution, you create an instance of the Thread class, or one of its subclasses. For example,
</P>
<!-- CODE SNIP //-->
<PRE>
Thread t = new Thread();
</PRE>
<!-- END CODE SNIP //-->
<P>instantiates a Thread object <I>t</I>. To start and stop the execution of <I>t</I>, use the Thread methods start() and stop():</P>
<!-- CODE SNIP //-->
<PRE>
t.start(); // start running Thread t
t.stop(); // stop running Thread t
</PRE>
<!-- END CODE SNIP //-->
<P>You can also suspend the execution of a thread, and resume it afterward:
</P>
<!-- CODE SNIP //-->
<PRE>
t.suspend(); // suspend execution of t
t.resume(); // resume execution of t
</PRE>
<!-- END CODE SNIP //-->
<P>A thread can suspend and resume as many times as you’d like, but it can only start and stop once. The life cycle of a thread is illustrated in Figure 10-2.
</P>
<P><A NAME="Fig2"></A><A HREF="javascript:displayWindow('images/10-02.jpg',600,411 )"><IMG SRC="images/10-02t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/10-02.jpg',600,411)"><FONT COLOR="#000077"><B>Figure 10-2</B></FONT></A> Life cycle of a thread</P>
<P>Now let’s see how to specify the code that the thread executes, once it’s alive. There are two ways of doing this: by creating a subclass of Thread and by doing something else.
</P>
<H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">Creating a Subclass of Thread</FONT></H4>
<P>In the first way, you create a subclass of Thread, and define a method called run(). When an instance of your subclass is alive, it will execute the code in the run() method. The thread is destroyed upon completion of the run() method.
</P>
<P>As an example, let’s derive a subclass of Thread called MyThread:</P>
<!-- CODE SNIP //-->
<PRE>
public class MyThread extends Thread {
...
public void run() {
...
}
}
</PRE>
<!-- END CODE SNIP //-->
<P>Now let’s create multiple instances of MyThread, and start them. Each thread will independently execute the code found in run().
</P>
<!-- CODE //-->
<PRE>
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
// start all three threads.
t1.start();
t2.start();
t3.start();
...
// suspend t1
t1.suspend();
...
// stop t3
t3.stop();
</PRE>
<!-- END CODE //-->
<H4 ALIGN="CENTER"><A NAME="Heading10"></A><FONT COLOR="#000077">Creating a Class That Implements Runnable</FONT></H4>
<P>The second way of telling a thread to execute your code is to create a class that implements the Runnable interface. You have already used this method to create animations in Chapter 2, Using Objects for Animation.
</P>
<P>A class that implements the Runnable interface provides the definition of a method called run():</P>
<!-- CODE SNIP //-->
<PRE>
class MyClass implements Runnable {
...
public void run() {
...
}
}
</PRE>
<!-- END CODE SNIP //-->
<P>Let’s create an instance of MyClass:
</P>
<!-- CODE SNIP //-->
<PRE>
MyClass c = new MyClass(); // create MyClass object
</PRE>
<!-- END CODE SNIP //-->
<P>Now create an instance of Thread while passing in the Runnable object.
</P>
<!-- CODE SNIP //-->
<PRE>
Thread t = new Thread(c);
</PRE>
<!-- END CODE SNIP //-->
<P>Once <I>t</I> starts, it executes the run() method of MyClass as a separate thread. The animation applets you’ve written work in this way. This method of creating threads comes in handy, for classes like Applet that don’t derive from Thread.</P>
<P>Now let’s see how a single CPU handles the concurrent execution of several threads.</P>
<H4 ALIGN="LEFT"><A NAME="Heading11"></A><FONT COLOR="#000077">Understanding Thread Scheduling</FONT></H4>
<P>Unlike most humans, computers can do more than one thing at a time (or so it seems). Since there’s usually a single CPU per computer, you might wonder how it executes multiple threads concurrently. The answer is simple: The CPU executes only one thread at a given moment, but it alternates between the various threads, running each in turn. For example, Figure 10-3 shows how processing time might be divided if you have three living threads in a Java program. As you see, each thread has the CPU for a moment. Then it waits for the CPU to execute it again.
</P>
<P><A NAME="Fig3"></A><A HREF="javascript:displayWindow('images/10-03.jpg',600,409 )"><IMG SRC="images/10-03t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/10-03.jpg',600,409)"><FONT COLOR="#000077"><B>Figure 10-3</B></FONT></A> Execution of three threads</P>
<P>The process of deciding which thread to run is called <I>thread scheduling</I>, and it’s done by the runtime environment. All threads have a <I>priority</I>, and those with higher priority are executed before those of lower priority. Priorities are integers between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY, and you can access the priority of a thread using the methods getPriority() and setPriority(int):</P>
<!-- CODE SNIP //-->
<PRE>
Thread t = new Thread();
t.setPriority(Thread.NORM_PRIORITY);
System.out.println("Priority:" + t.getPriority());
</PRE>
<!-- END CODE SNIP //-->
<P>When two threads have equal priority, the manner in which these threads are executed depends on the particular platform. For time-slicing systems (such as those running UNIX), the two threads will alternate execution. On other platforms, the scheduler will execute one thread until it’s finished, before moving on to other threads of equal priority. (Needless to say, this sounds a little unfair!)
</P>
<P>However, a thread can <I>yield</I> to other threads of equal priority, using the instance method yield():</P>
<!-- CODE SNIP //-->
<PRE>
t.yield();
</PRE>
<!-- END CODE SNIP //-->
<P>This allows other threads that are waiting for processing time to be executed. Figure 10-4 shows how two threads that use yield() might be executed.
</P>
<P><A NAME="Fig4"></A><A HREF="javascript:displayWindow('images/10-04.jpg',600,407 )"><IMG SRC="images/10-04t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/10-04.jpg',600,407)"><FONT COLOR="#000077"><B>Figure 10-4</B></FONT></A> Using yield()</P>
<P>When you’re writing a program that uses multiple threads, it’s good practice to use yield(), as you’ll see later on. Of course, a thread also gives up the CPU to other threads when it executes sleep(), suspend(), or stop().
</P>
<P>Now, let’s look at a simple example of threads in action!</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="353-358.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="363-368.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -