📄 when.html
字号:
<html><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><html> <head><title>When to Create Threads</title></head><BODY bgcolor=#ffffee vlink=#0000aa link=#cc0000><h1>When to Create Threads</h1>Deciding whether an activity should be accompanied by construction ofa thread requires balancing constraints including:<dl><dt> Concurrency Management<dd> Many programs interacting with users need to perform screen updates, respond to inputs, and send and receive messages over networks, all in an intrinsically concurrent fashion. While it might be possible to program such systems by manually arranging interleaving among such activities, it is hopelessly complicated, fragile, and error-prone. Such designs are substantially simpler to express, code, understand, maintain, and extend in multithreaded form.<dt> Availability<dd> One reason for creating new threads is to maintain high availability of services. For example, among the more common active object designs (used, for example in Unix <CODE>inetd</CODE>) is to have one object serving as a <a href="service.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html">gateway</a> interface to a service. It handles each request by constructing a new active object to asynchronously service the request. The gateway is thus able to accept another request quickly. This helps avoid bottlenecks by draining the network of pending messages.<dt> Controllability<dd> Activities within threads can be suspended, resumed, and stopped by other objects.<dt> Thread Overhead<dd> Constructing a thread and setting it in motion is costlier (i.e., slower and more resource-intensive) than constructing a `normal' (passive) object and/or invoking a method on it. If an activity is only a matter of a couple of primitive statements, then it would be much faster just to handle it synchronously than to use threads. This is usually true even when the activity should conceptually be asynchronous. Logical asynchrony does not always have to translate into actual asynchrony. Logical asynchrony means that a client is not directly affected by (or doesn't care about) when an activity begins or when it ends. In some cases, it might as well begin right when the client invokes it, blocking the client from doing anything else while it takes place, and then end sometime later at which point the client continues on. If this is acceptable, the interaction can be converted to use standard Java method calls. <dt> Intrinsic Concurrency<dd> When one object must logically wait for a reply from another in order to continue, the same process/thread may be used to implement the entire call-execute-reply activity without any loss of concurrency. Constructing a new thread in such a case would achieve no benefit. <dt> Proceduralness<dd> An activity running as a thread cannot use call-reply procedural message passing style in which a client sends arguments to a procedure, waits for it to process them, and receives a reply. While these effects can be obtained in threads, they require manual coding, normally via <a href="service.html#secCallbacks" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html#secCallbacks">callbacks</a>. <dt> Objects versus Activities<dd> In essentially all OO systems, at any given time, there will be many fewer asynchronously executing concurrent activities than there are objects. Thus, even from a <a href="models.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/models.html">per-object concurrency</a> approach, it only makes sense to create a new thread when an invocation (message send) actually creates a new asynchronous activity, not automatically whenever constructing a new object that may or may not ever engage in asynchronous activities.<dt> Safety<dd> When multiple threads are not completely independent (i.e., they involve objects sending messages to others that may also be involved in other threads), all of these objects must utilize <a href="synchDesign.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/synchDesign.html">synchronization</a> mechanisms to ensure that they maintain consistent state. Attempts to use multiple threads involving objects that were designed to work only in sequential settings lead to random, hard to debug inconsistencies.</dl><h2>Object Responsibilities</h2>Most differences among designs using Threads stem fromdifferences in which objects are responsible for doing what. Inall cases there are at least two conceptual parties, butat least three implementation-level objects:<ul> <li> The Client, who wants an activity performed. <li> The Server containing the code to perform the activity. <li> The Thread that runs the activity asynchronously.</ul>Across these ``two-party'' cases, the underlying mechanics for differentThread-based patterns are very similar, but differ in whether threads(and sometimes associated helper objects) are generated by the client,by the server, or by the activity itself:<ul> <li> In <a href="waiters.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/waiters.html"> Waiter Threads </a>, the client builds a special <code>Runnable</code> helper class that invokes the Server method, and starts up the helper in a Thread. <li> In <a href="early.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/early.html"> Early Reply Threads</a>, the Server starts up a thread in response to a message from the client. <li> In <a href="service.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html"> Service Threads</a>, the Server class itself is (re)designed so that the activity is accessed via <code>run</code> rather than through a normal method call, thus turning it into a stand-alone entity easily runnable as a thread. <a href="auton.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/auton.html"> Autonomous Loops</a> represent essentially the same design but apply when the service activity need never terminate. (Conceptually, in both cases the activity itself initiates a thread, but in practice it is more flexible, controllable, and thus preferable to have the client actually perform the associated thread <code>start</code>.)</ul><p> Each of these patterns includes some guidelines describing whereit is most appropriate. However, in OO designs. Servers with respectto one method call are also Clients with respect to any calls they inturn make in their methods, so there's often a lot of flexibility inchoosing which way to go. Additionally, each of these patternsincludes subpatterns (including <ahref="service.html#secCallbacks" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html#secCallbacks">Completion Callbacks</a>, <ahref="service.html#Gateways" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/service.html#Gateways">Gateways</a>, <ahref="waiters.html#secJoining" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/waiters.html#secJoining">Joining</a>, <ahref="early.html#secLimiting" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/early.html#secLimiting">Limiting Thread Creation</a>, and <ahref="auton.html#secYielding" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/auton.html#secYielding">Yielding</a>) that are most closelyassociated with their containing patterns, but also occasionally applyin the others.<p>These patterns can be extended in several ways to apply tolarger-scale designs. The <a href="activityFlow.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/activityFlow.html"> Activity Flow</a>pattern (including several subpatterns and variants) describesdesigns in which possibly many objects participate in a seriesof steps required to fullfill some common functionality.<p><a href="aopintro.html" tppabs="http://www.foi.hr/~dpavlin/java/mirrors/g.oswego.edu/dl/pats/aopintro.html">[Concurrent Programming in Java]</a><hr><address><A HREF="javascript:if(confirm('http://g.oswego.edu/dl \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'" tppabs="http://g.oswego.edu/dl">Doug Lea</A></address><!-- hhmts start -->Last modified: Tue Feb 20 06:27:20 EST 1996<!-- hhmts end --></body> </html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -