Concurrent Programming in Java

5星(超过95%的资源)
所需积分/C币:45 2014-01-15 19:01:20 2.42MB PDF
35
收藏 收藏
举报

多线程编程的java实现。 备注:自2014年1月14日起,本人上传的经典书籍,将不再收取资源分,欢迎大家下载学习,好东西一起分享,共同建造良好的网上学习环境。
THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN: THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS INC MAY MAKE IMPROVEMENTS ANDOR CHANGES IN ANY TECHNOLOGY PRODUCT OR PROGRAM DESCRIBED IN THIS PUBLICATION AT ANY TIME The author and publisher have taken care in the preparation of this document, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use ofthe information or programs contained herein Library of congress card Number 99-066823 Copyright C) 2000 by Addison Wesley longman, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada Text printed on recycled and acid-free paper 234567-MA-02010099 Second printing, November 1999 Acknowledgments This book began as a small set of Web pages that I put together in spring 1995, while trying to make sense of my own early attempts to use Java concurrency features in experimental development efforts Then it grew; first on the World Wide Web, where I extended, expanded, and removed patterns to reflect my and other people s increasing experience with Java concurrency: and now into this book, which places patterns within the broader perspective of concurrent software development. The web pages also live on, but they now serve as a supplement to the conceptual presentations best suited to book form There have been many changes along the way, in a process that has benefited from commentary, suggestions, errata reports, and exchanges with many kind and knowledgeable people. These include Ole Agesen, Tatsuya Aoyagi, Taranov Alexander, Moti Ben-Ari, Peter Buhr, Bruce Chapman, Il Hyung Cho, Colin Cooper, Kelly Davis, Bruce Eckel, Y acov Eckel, Saleh Elmohamed, Ed Falis Randy Farmer, Glenn Goldstein, David Hanson, Jyrki Heikkinen, Alain Hsiung, Jerry ames Johannes Johannsen, Istvan Kiss, Ross Knippel, Bil Lewis, Sheng liang, Jonathan Locke, Steve MacDonald, Hidehiko Masuhara, Arnulf Mester, Mike Mills, Trevor Morris, Bill Pugh, Andrew Purshottam, Simon Roberts, John rose, Rodney ryan, Joel Rosi-Schwartz, Miles Sabin, Aamod Sane Beverly Sanders, Doug Schmidt, Kevin Shank, Yukari Shirota, David Spitz, David Stoutamire, Henry Story, Sumana Srinivasan, Satish Subramanian, Jcff Swartz, Patrick Thompson, Volker Turau, Dennis Ulrich, Cees Vissar, Bruce Wallace, Greg Wilson, Grant Woodside, Steve Yen, and Dave Yost, as well as people who submitted anonymous electronic mail commentary Thc members of Ralph Johnson,'s patterns seminar (especially brian Footc and lan Chai) rcad througl early forms of some patterns and suggested many improvements. Raj Datta, Sterling Barrett, and Philip eskelin of the New York City Patterns Group, and Russ rufer, Ming Kwok, Mustafa Ozgen, Edward Andcrson, and Don Chin of the Silicon Valley Patterns Group pcrformcd similar valuable service for preliminary versions of the second edition Official and unofficial reviewers of the first-and second-edition manuscripts made helpful comments and suggestions on tight schedules. They include Ken Arnold, Josh Bloch, Joseph Bowbeer, Patrick Chan, Gary Craig, Desmond D'Souza, Bill Foote, Tim Harrison, David Henderson, Tim Lindholm, Tom May, Oscar NierstraSz, James Robins, Greg Travis, Mark Wales, Peter Welch, and Debora Zukowski. Very special thanks go to Tom Cargill for his many insights and corrections, as well as for permission to include a description of his Specific Notification pattern. Very special thanks also go to David Holmes for, among many contributions, helping to develop and extend material for tutorials that in turn became included in the second edition Rosemary Simpson contributed numerous improvements in the course of creating the index. Ken Arnold patiently helped me deal with FrameMaker. Mike Hendrickson and the editorial crew at Addison-Wesley have been continually supportive This book would not have been possible without the generous support of Sun Labs. Thanks especially to Jos Marlowe and Steve Heller for providing opportunities to work collaboratively on fun and exciting research and development projects Thanks above all to Kathy, Keith, and Colin for tolerating all this Doug lea, september 1999 Chapter 1. Concurrent Object-Oriented Programming This book discusses some ways of thinking about, designing, and implementing concurrent programs in the avaTM programming language. Most presentations in this book assume that you are an experienced developer familiar with object-oriented(oo) programming, but have little exposure to concurrency. readers with the opposite background-experience with concurrency in other languages may also find this book useful The book is organized into four coarse-grained chapters (Perhaps parts would be a better term. ) This first chapter begins with a brief tour of some frequently used constructs and then backs up to establish a conceptual basis for concurrent object-oriented programming how concurrency and objects fit together, how the resulting design forces impact construction of classes and components and how some common design patterns can be used to structure solutions The three subsequent chapters are centered around use(and evasion )of the three kinds of concurrency constructs found in the Java programming language Exclusion. Maintaining consistent states of objects by preventing unwanted interference among concurrent activities, often using synchronized methods State dependence. Triggering, preventing, postponing, or recovering from actions depending on whether objects are in states in which these actions could or did succeed, sometimes using monitor methods Object. wait, object notify, and object. notifyAll Creating threads. establishing and managing concurrency, using Thread objects Each chapter contains a sequence of major sections, each on an independent topic. They present high- level design principles and strategies, technical details surrounding constructs, utilities that encapsulate common usages and associated design patterns that address particular concurrency problems. Most sections conclude with an annotated sel of further readings providing more information on selected topics. The online supplement to this book contains links to additional online resources, as well as updates, errata, and code examples. It is accessible via links from http:/iava.sun.com/seriesorhttp:/gee.cs.oswego.edu/dl/cpi If you are already familiar with the basics, you can read this book in the presented order to explore each topic in more depth But most readers will want to read this book in various different orders Because most concurrency concepts and techniques interact with most others, it is not always possible to understand each section or chapter in complete isolation from all the others. However, you can still take a breadth-first approach, briefly scanning each chapter (including this one) before proceeding with more detailed coverage of interest. Many presentations later in the book can be approached after selectively reading through earlier material indicated by extensive cross-references You can practice this now by skimming through the following preliminaries Terminology. This book uses standard oo terminological conventions: programs define methods (implementing operations ) and fields (representing attributes) that hold for all instances(objects of specified classes Interactions in Oo programs normally revolve around the responsibilities placed upon a client object needing an action to be performed, and a server object containing the code to perform the action. The terms client and server are used here in their generic senses, not in the specialized sense of distributed client/ server architectures. a client is just any object that sends a request to another object, and a server is just any object receiving such a request. Most objects play the roles of both clients and servers. In the usual casc whcrc it docsn't matter whether an object under discussion acts as a client or server or both, it is usually called a host; others that it may in turn interact with are often called helpers or peers. Also, when discussing invocations of the form obj. msg(arg), the recipient (hat is, the object bound to variable obj) is called the target object This book generally avoids dealing with transient facts about particular classes and packages not directly related to concurrency. And it does not cover details about concurrency control in specialized frameworks such as Enterprise JavaBeans TM and Servlets. But it does sometimes refer to branded software and trademarked products associated with the Java TM Platform. The copyright page of this book provides more information Code listings. Most techniques and patterns in this book are illustrated by variants of an annoyingly small set of toy running examples. This is not an effort to be boring, but to be clear. Concurrency constructs are often subtle enough to get lost in otherwise meaningful examples. Reuse of running examples makes small but critical differences more obvious by highlighting the main design and implementation issues. Also, the presentations include code sketches and fragments of classes that illustrate implementation techniques, bul are not intended to be complete or even compilable. These classes are indicated by leading comments in the listings mport statements, access qualifiers, and even methods and fields are sometimes omitted from listings when thcy can bc inferred from context or do not impact rclcvant functionality. Thc protected qualifier is uscd as a default for non-public fcaturcs whenever thcrc is no particular reason to restrict subclass access. This emphasizes opportunities for extensibility in concurrent class design(see$ 1.3.4 and$3.3.3). Classes by default have no access qualifier. Sample listings are sometimes formatted in nonstandard ways to kccp thcm togcthcr on pages or to emphasize thc main constructions of intcrcst. The code for all example classes in this book is available from the online supplement. most techniques and patterns in this book are illustrated by a single code example showing their most typical forms The supplement includes additional examples that demonstrate minor variations, as well as some links to other known usages It also includes some larger examples that are more useful to browse and experiment with online than to read as listings The supplement provides links to a package, util. concurrent, that contains production quality versions of utility classes discussed in this book. This code runs on the Java 2 Platform and has been tested with 1. 2. x releases Occasional discussions asides and footnotes briefly mention changes from previous releases potential future changes known at the time of this writing and a few implementation quirks to watch out for. Check the online supplement for additional updates Diagrams. Standard uml notation is used for interaction and class diagrams(see the Further Readings in$ 1.1.3). The accompanying diagrams (courtesy of Martin Fowler) illustrate the only forms used in this book. Other aspects of UML notation, methodology, and terminology are not specifically relied on an Obiect Interaction diagram create new Obiect message self-call rel turn Inany Class Class name (zero or more tional class Class Name (zero or one attribute [ Type initial valule Class K> aggregation operation [(arg list) return type] field or role name Source Target Note some useful text Interface or sample code Superclass Implementing Class Subclass 1 Subclass 2 Most other diagrams show timethreads in which free-form gray curves trace threads traversing hrough collections of objects. Flattened arrowheads represent blocking Objects are depicted as ovals that sometimes show selected internal features such as locks, fields, and bits of code. Thin(usually labeled) lines between objects represent relations(normally references or potential calls) between them. Here's an otherwise meaningless example showing that thread a has acquired the lock for object X, and is proceeding through some method in object Y that serves as a helper to X thread B is meanwhile somehow blocked while entering some method in object X: Thread B lock object X hel obiect Y Thread a 1.1 Using Concurrency Constructs This section introduces basic concurrency support constructs by example and then proceeds with a walk-through of the principal methods of class Thread. Other concurrency constructs are briefly described as thcy arc introduccd, but full tcchnical details arc postponcd to latcr chapters(mainly 2. 2. 1 and 3.2.2). Also, concurrent programs often make use of a few ordinary Java programming language features that are not as widely used elsewhere. These are briefly reviewed as they arise 1.1.1 A Particle applet ParticleApplet is an Apple t that displays randomly moving particles. In addition to concurrency constructs, this example illustrates a few of the issues encountered when using threads with any GUl-based program. The version described here needs a lot of embellishment to be visually attractive or realistic. You might enjoy experimenting with additions and variations as an exercise As is typical of GUI-based programs, ParticleApplet uses several auxiliary classes that do most of thc work. Wcll stcp through construction of the Particle and Particlecanvas classes before discussing ParticleApplet java awrt Canvas javaappletApplet canvas Particlecanvas ParticleApplet paint particles 101t Particle start <<infare>> s top x, y java. lang. Runnable move run draw java.lang Thread threads Kanon Runnable start runnable Interrupt run sleep 11. Partice The Particle class defines a completely unrealistic model of movable bodies. Each particle is represented only by its(x, y)location. Each particle also supports a method to randomly change its location and a method to draw itself (as a small square)given a supplied java. awt. Graphics object While particle objects do not themselves exhibit any intrinsic concurrency, their methods may be invoked across multiple concurrent activities. when one activity is performing a move and another is invoking draw at about the same time we'd like to make sure that the draw paints an accurate representation of where the Particle is here, we require that draw uses the location values current either before or after the move. For example, it would be conceptually wrong for a draw operation to display using the y-value current before a given move, but the x-value current after the move. If we were to allow this, then the draw method would sometimes display the particle at a location that it never actually occupied This protection can be obtained using the synchronized keyword, which can modify either a method or a block of code. Every instance of class Object(and its subclasses) possesses a lock that is obtained on entry to a synchronized method and automatically released upon exit. The code- block version works in the same way except that it takes an argument stating which object to lock. The most common argument is this, meaning to lock the object whose method is executing when a lock is held by one thread, other threads must block waiting for the holding thread to release the lock Locking has no effect on non-synchronized methods, which can execute even if the lock is being held by another thread Locking provides protection against both high-level and low-level conflicts by enforcing atomicity among methods and code-blocks s ynchronized on the same object. Atomic actions are performed as units, without any interleaving of the actions of other threads But, as discussed in 1.3.2 and in Chapter 2, too much locking can also produce liveness problems that cause programs to freeze up. Rather than exploring these issues in detail now, we'll rely on some simple default rules for writing mcthods that prccludc intcrfcrcncc problcms Always lock during updates to object fields. always lock during access of possiblv updated object fields Never lock when invoking methods on other objects. These rules have many exceptions and refinements, but they provide enough guidance to write class Particle: import java.util. Random; class particle i protected int xi protected int yi protected final Random rng new Random()i public Particle(int initial, int initialy) i initial; y - initially public synchronized void move( x + rng. nextInt(10)-5 y + rng. nextInt(20)-10i public void draw(Graphics g) i int lx, lyi synchronized (this) xily } g drawRect(lx, ly, 10, 10) Notes: The use of final in the declaration of the random number generator rng reflects our decision that this reference field cannot be changed, so it is not impacted by our locking rules Many concurrent programs usc final cxtcnsivcly, in part as helpful, automaticall enforced documentation of design decisions that reduce the need for synchronization(see 8 2.1) The dr aw method needs to obtain a consistent snapshot of both the x and y values. Since a single method can return only one value at a time and we need both the x and y values here we cannot easily encapsulate the field accesses as a synchronized method. We instead use a synchronized block (Sees 2. 4 for some alternatives. The dr aw method con forms to our rule of thumb to release locks during method invocations on other objects (here g. drawrect). The move method appears to break this rule by calling rng. nextInt. However, this is a reasonable choice here because each Particle confines its own rng-conceptually, the rng is just a part of the Particle itself. so it doesn 't count as an"other"object in the rule. Section$2. 3 describes more general conditions under which this sort of reasoning applies and discusses factors that should be taken into account to be sure thal this decision is warranted 1.1.1.2 Partic/e canvas Particlecanvas is a simple subclass ofjava. awt. Canvas that provides a drawing area for all of the Particles. Its main responsibility is to invoke draw for all existing particles whenever its paint method is called However, the Particlecanvas itself does not create or manage the particles. It needs either to be told about them or to ask about them here we choose the former The instance variable particles holds the array of existing Particle objects. This field is set when necessary by the applet, but is used in the paint method. We can again apply our default known as accessor and assignment methods)forparticles, otherwise avoiding direct access r o rules, which in Chis case lead to the creation oflillle synchronized get and set methods (also the particles variable itself. To simplify and to enforce proper usage, the particles field is never allowed to be null. It is instead initialized to an empty array class particlecanvas extends canvas private Particle[ particle ew Particle[oli Particlecanvas (int size) setsize(new Dimension(size, size))i // intended to be called by applet protected synchronized void setparticles(Particle[] ps)t f(p nu11) throw new IllegalArgumentException( Cannot set null)i particles =ps;

...展开详情
试读 127P Concurrent Programming in Java
立即下载 身份认证后 购VIP低至7折
一个资源只可评论一次,评论内容不能少于5个字
jhtloveyou 很经典的书籍,很不错!
2019-05-06
回复
wtbee 谢谢分享,正好使用上。
2018-04-25
回复
玖富 不错正版的,好人一生平安,谢谢楼主
2018-02-12
回复
qwesdfok 这书内容写的不错
2017-10-13
回复
dingxiasnghua1234 不错,很好的书
2017-06-04
回复
hakula007 是一本好书,推荐
2016-12-27
回复
林家小米 经典书籍,concurrent包下的类很重要
2016-10-20
回复
nuoboxgx 好书,下载回来一直在看
2016-10-14
回复
wwee3688 好书很经典,文字清晰,感谢分享
2016-10-11
回复
生命之诞 感谢分享,经典好书
2016-09-22
回复
您会向同学/朋友/同事推荐我们的CSDN下载吗?
谢谢参与!您的真实评价是我们改进的动力~
  • GitHub

  • 签到新秀

  • 分享王者

关注 私信
上传资源赚钱or赚积分
最新推荐
Concurrent Programming in Java 45积分/C币 立即下载
1/127
Concurrent Programming in Java第1页
Concurrent Programming in Java第2页
Concurrent Programming in Java第3页
Concurrent Programming in Java第4页
Concurrent Programming in Java第5页
Concurrent Programming in Java第6页
Concurrent Programming in Java第7页
Concurrent Programming in Java第8页
Concurrent Programming in Java第9页
Concurrent Programming in Java第10页
Concurrent Programming in Java第11页
Concurrent Programming in Java第12页
Concurrent Programming in Java第13页
Concurrent Programming in Java第14页
Concurrent Programming in Java第15页
Concurrent Programming in Java第16页
Concurrent Programming in Java第17页
Concurrent Programming in Java第18页
Concurrent Programming in Java第19页
Concurrent Programming in Java第20页

试读结束, 可继续阅读

45积分/C币 立即下载