?? javaconc.html
字號:
<html><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><html> <head><title>Basic Concurrency Mechanics in Java</title></head><BODY bgcolor=#ffffee vlink=#0000aa link=#cc0000><h1>Basic Concurrency Mechanics in Java</h1>Support for threads in Java revolves around class <code>Thread</code>.Please take a minute to quickly browse through the standard <ahref="javascript:if(confirm('http://g.oswego.edu/dl/java/api/java.lang.Thread.html \n\nThis file was not retrieved by Teleport Pro, because it is addressed on a domain or path outside the boundaries set for its Starting Address. \n\nDo you want to open it from the server?'))window.location='http://g.oswego.edu/dl/java/api/java.lang.Thread.html'" tppabs="http://g.oswego.edu/dl/java/api/java.lang.Thread.html">JavaDocumentation for Class Thread</a> to become familiar with some of thefeatures and method names before continuing.<p>Contents:<ul> <li> <a href="#secRunnable">Runnable Objects</a> -- Defining activities and setting them in motion. <li> <a href="#secControl">Controlling Activities</a> -- Stopping, suspending, sleeping, prioritizing, grouping. <li> <a href="#secSynch">Synchronization</a> -- Protecting objects from interference. <li> <a href="#secOther"> Other Mechanisms</a> -- Links to discussions of built in Java capabilities discussed elsewhere.</ul><h2><a name="secRunnable"></a>Runnable Objects</h2><code>Thread</code> is the base class for all objects that can behaveas threads. However, often enough you can use threads in Java withoutever dealing with anything about <code>Threads</code> exceptconstructing them and setting them in action. <p>The main thing that a Thread can do is <code>run()</code>. EveryThread-based class must define a void method named <code>run()</code>that can be asynchonously executed. The method can do anything at all(except that it can't take arguments and can't return results). It isjust an ordinary method with a special name.<p> In fact <code>run()</code>ing is <em>all</em> that most threadsdo. To make this easier to deal with, Java supplies a simple interface<code>java.lang.Runnable</code>:<pre>public interface Runnable { public abstract void run();}</pre><p>(For a brief introduction to the role of interfaces in OO design,see <a href="ifc.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/ifc.html"> here</a>.)<p> Any new class can implement <code>Runnable</code> simply bydefining a <code>run()</code> method. For example, here's a specialRunnable class (an example of the <a href="service.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html">service</a>pattern) that just prints a message. (It uses AWT TextArea rather thanjust printing to a stream so that it is easily viewable in an applet.)<pre>public class SimpleMessagePrinter implements Runnable { protected String msg_; // The message to print protected TextArea txt_; // The place to print it public SimpleMessagePrinter(String m, TextArea txt) { msg_ = m; txt_ = txt; } public void run() { txt_.appendText(msg_); txt_.repaint(); }}</pre>(Full Java source files for this and other demo classes can befound <a href="javascript:if(confirm('http://g.oswego.edu/dl/classes/aop/index.html \n\nThis file was not retrieved by Teleport Pro, because it is addressed on a domain or path outside the boundaries set for its Starting Address. \n\nDo you want to open it from the server?'))window.location='http://g.oswego.edu/dl/classes/aop/index.html'" tppabs="http://g.oswego.edu/dl/classes/aop/index.html">here</a>.)<p> Objects of this class could be used in two ways. The first is justto call <code>run</code> directly from another object in the usualway. For example, from Applet<code>SimpleMessageAppletV1</code>. (Note: We use here the Appletconventions of initializing ``intrinsic'' instance variables in theApplet constructor, initializing from Applet parameters and performinglayout in <code>init</code>, and starting up the main Appletfunctionality in <code>start()</code>.)<pre>public class SimpleMessageAppletV1 extends Applet { protected TextArea txt_; protected SimpleMessagePrinter hello_; protected SimpleMessagePrinter goodbye_; public SimpleMessageAppletV1() { txt_ = new TextArea(4, 40); txt_.setEditable(true); hello_ = new SimpleMessagePrinter("Hello\n", txt_); goodbye_ = new SimpleMessagePrinter("Goodbye\n", txt_); } public void init() { setLayout(new BorderLayout()); add("South", txt_); } public void start() { hello_.run(); goodbye_.run(); } }</pre><a href="SimpleMessageAppletV1.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/SimpleMessageAppletV1.html">Run SimpleMessageAppletV1</a>.<p> The second way is to create a new Thread around the Runnableobject, which when started, will execute the Runnable's run() method:<pre>public class SimpleMessageAppletV2 extends SimpleMessageAppletV1 { public SimpleMessageAppletV2() { super(); } public void init() { super.init(); add("North", new Button("Restart")); } public void start() { Thread ht = new Thread(hello_); Thread gt = new Thread(goodbye_); ht.start(); gt.start(); } public boolean action(Event evt, Object arg) { if ("Restart".equals(arg)) { start(); return true; } return false; }}</pre><a href="SimpleMessageAppletV2.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/SimpleMessageAppletV2.html">Run SimpleMessageAppletV2</a>.<p> These two Applets may or may not have the same overall effect.Because the second one runs these methods in two different threads, itmay be that the "Goodbye" thread actually executes its<code>appendText</code> first. (Try hitting <em>Restart</em> a fewtimes in the Applet to see if you can get this to happen.)<p> Note: The name of the method you <em>define</em> is<code>run()</code>, but the name of the method you <em>call</em> inthe Thread is <code>start()</code>. In other words,<code>Thread.start()</code> causes <code>Runnable.run()</code> to runin a thread. Even more confusingly, <code>Thread.start()</code> is notdirectly related to method <code>Applet.start()</code> even thoughthey share the same name.<h3>Runnables versus Thread Subclasses</h3>There are two ways to use the <code>Thread</code> class:<ol> <li> As above, by implementing <code>Runnable</code>, and starting new activities by wrapping them inside <code>Threads</code> created with the <code>Thread(Runnable)</code> constructor. <li> By subclassing <code>Thread</code>, overriding the <code>run</code> method.</ol> <p> While either way works, the <code>Runnable</code> approach has afew advantages that make it the default strategy of choice:<ul> <li> <em>ANY</em> java method can include code of the form: <pre>Thread mythread = Thread.currentThread();</pre> and then use <code>mythread</code> to call other public <code>Thread</code> methods on the Thread it is running in. If you need to <em>change</em> the way that any of these methods are defined, you need to subclass <code>Thread</code>. But if you just want to define the activities taking place within threads in a way that can still invoke Thread methods, it is simpler just to implement <code>Runnable</code>. <li> If someone else were to build a special <code>Thread</code> subclass; say <code>AutoReprioritizingThread</code>, that added to or altered the way activities were controlled, a <code>Runnable</code> would still be excutable within it, but a <code>Thread</code> subclass normally would not be. <li> Because <code>Runnable</code> is an interface, not a class, you can add run-ability as a ``mixin'' to any arbitrary subclass. For a simple but tasteless example:<pre>class MyDate extends java.util.Date implements Runnable { public void run() { System.out.println("Day of the week: " + getDay()); }}</pre></ul><p> As a special case, it sometimes works out well to make an Appletitself implement <code>Runnable</code>. This can simplifyimplementation, but applies only when only one kind of activity isbeing controlled by the Applet. (The technique is not very workable ifmore than one kind of activity is being controlled.) For example,here is another version of SimpleMessageApplet, made by merging partsof the <code>SimpleMessagePrinter</code> and<code>SimpleMessageApplet</code> classes (as described in the <ahref="early.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/early.html">early reply</a> pattern). This one fires up only onekind of thread (not two), so is not very interesting:<pre>public class SimpleMessageAppletV3 extends Applet implements Runnable{ protected TextArea txt_; protected SimpleMessagePrinter hello_; protected SimpleMessagePrinter goodbye_; protected String msg_; public SimpleMessageAppletV3() { txt_ = new TextArea(4, 40); txt_.setEditable(true); msg_ = "Hello\n"; } public void init() { setLayout(new BorderLayout()); add("South", txt_); add("North", new Button("Restart")); } public void start() { Thread ht = new Thread(this); ht.start(); } public boolean action(Event evt, Object arg) { if ("Restart".equals(arg)) { start(); return true; } return false; } public void run() { txt_.appendText(msg_); txt_.repaint(); }}</pre><a href="SimpleMessageAppletV3.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/SimpleMessageAppletV3.html">Run SimpleMessageAppletV3</a>.<h2><a name="secControl"></a>Controlling Activities</h2>The most commonly used <code>Thread</code> methods are those thatcause threads not to do anything at all. Normally a thread stops whenit hits the end of its <code>run</code> method. However, sometimes youneed to stop activities for other reasons or in other senses. Thereare several levels of ``severity'' for halting activities in threads,including:<ul> <li> <code>destroy()</code> stops and kills a thread without giving it or the Java runtime any chance to intervene. It is not recommended for routine use. <li> <code>stop()</code> stops and kills a thread in a way that the Java runtime can clean up after it. This is the most common way of stopping threads. Note that stopping a thread does <em>NOT</em> kill the <code>Thread</code> object itself just the activity. <li> <code>interrupt()</code> causes any kind of wait (<code>sleep()</code>, <code>wait()</code>, <code>join()</code>, etc) to abort with an <code>InterruptedException</code>, which can be caught and dealt with in an application-specific way.
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -