Core Java 2, Vol. I--Fundamentals

Transcription

Core Java 2: Volume II–Advanced FeaturesBy Cay S. Horstmann, Gary Cornell ExamplesPublisher: Prentice Hall PTRPub Date: December 13, 2001ISBN: 0-13-092738-4Pages: 1232An indispensable companion to the best-selling Core Java 2, Vol. I--Fundamentals (0-13089468-0), Core Java 2, Volume II: Advanced Features is now available in a revised andexpanded fifth edition. It delivers the same real-world guidance you need to solve even themost challenging programming problems and offers an all-new chapter on XML and Java, plusthoroughly revamped coverage of many advanced features—from collections to nativemethods, security to Swing.Cay Horstmann identifies the problems experienced Java platform developers encounter mostoften, and delivers insightful, expert-level guidance for addressing them-together with evenmore of the robust, sample code that have made Core Java an international bestseller for fivestraight years. You'll gain new insights into networking, remote objects, JDBC API,internationalization, and a whole lot more.For experienced programmers, Core Java 2, Volume 2: Advanced Features provides theanswers that they need to take full advantage of the power of Java technology and to get thejob done as efficiently as possible.State-of-the-art information for advanced Java technology development, including:zThoroughly updated coverage of multithreading, collections, and networkingzCompletely revised coverage of remote objectszDetailed new chapter on XML and JavazSophisticated new techniques for utilizing JavaBeans(tm) component architecturezAdvanced GUI-building techniques leveraging both Swing and AWTCopyrightList of Tables, Code Examples, and FiguresPrefaceAcknowledgmentsChapter 1. MultithreadingChapter 2. CollectionsChapter 3. NetworkingChapter 4. Database Connectivity: JDBCChapter 5. Remote ObjectsChapter 6. Advanced SwingChapter 7. Advanced AWTChapter 8. JavaBeans Chapter 9. Security

Chapter 10. InternationalizationChapter 11. Native MethodsChapter 12. XMLCopyright 2002 Sun Microsystems, Inc.—Printed in the United States of America.901 San Antonio Road, Palo Alto, California94303 U.S.A.All rights reserved. This product and related documentation are protected by copyright anddistributed under licenses restricting its use, copying, distribution, and decompilation. No partof this product or related documentation may be reproduced in any form by any means withoutprior written authorization of Sun and its licensors, if any.RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United StatesGovernment is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR52.227-19.The products described may be protected by one or more U.S. patents, foreign patents, orpending applications.TRADEMARKS—Sun, Sun Microsystems, the Sun logo, Java, and all Java-based trademarksare trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and othercountries.The publisher offers discounts on this book when ordered in bulk quantities. For moreinformation, contact: Corporate Sales Department, Phone: 800-382-3419; Fax: 201-236-7141;E-mail: corpsales@prenhall.com; or write: Prentice Hall PTR, Corp. Sales Dept., One LakeStreet, Upper Saddle River, NJ 07458.Editorial/production supervision: Navta AssociatesAcquisitions editor: Gregory G. DoenchEditorial assistant: Brandt KennaManufacturing manager: Alexis R. Heydt-LongCover design director: Jerry VottaCover designer: Talar Agasyan-BoorujyCover illustration: Karen Strelecki

Marketing manager: Debby van DijkProject coordinator: Anne GarciaInterior designer: Gail Cocker-BoguszSun Microsystems Press:Marketing manager: Michael Llwyd AlreadPublisher: Rachel Borden10 9 8 7 6 5 4 3 2Sun Microsystems PressA Prentice Hall TitleList of Tables, Code Examples, and FiguresTables2-1 Hash codes resulting from the hashCode function2-2 Hash codes of objects with identical contents2-3 Adding elements into hash and tree sets3-1 Convenience methods for response header values4-1 The Authors table4-2 The Books table4-3 The BooksAuthors table4-4 The Publishers table4-5 SQL Data Types4-6 SQL data types and their corresponding Java language types4-7 Selected queries4-8 ResultSet type values4-9 ResultSet concurrency values

4-10 Five columns of the result set5-1 Naming conventions for RMI classes6-1 Default renderers6-2 Resize modes7-1 The Porter-Duff Composition Rules7-2 Rendering Hints7-3 Document Flavors for Print Services7-4 Printing Attributes7-5 Capabilities of the Java data transfer mechanism7-6 Data Transfer Support in Swing Components9-1 Call stack during permission checking9-2 Permissions and their associated targets and actions10-1 Common ISO-639 language codes10-2 Common ISO-3166 country codes10-3 Collations with different strengths10-4 String selected by ChoiceFormat11-1 Java types and C types11-2 Correspondence between Java array types and C types12-1 Rules for Element Content12-2 Attribute types12-3 Attribute defaultsCode Examples1-1 Bounce.java1-2 BounceThread.java1-3 BounceExpress.java

1-4 BounceSelfish.java1-5 UnsynchBankTest.java1-6 SynchBankTest.java1-7 SwingThreadTest.java1-8 Animation.java1-9 TimerTest.java1-10 ProgressBarTest.java1-11 ProgressMonitorTest.java1-12 ProgressMonitorInputStreamTest.java1-13 PipeTest.java2-1 LinkedListTest.java2-2 SetTest.java2-3 TreeSetTest.java2-4 MapTest.java2-5 ShuffleTest.java2-6 SystemInfo.java2-7 CustomWorld.java2-8 Sieve.java2-9 Sieve.cpp3-1 SocketTest.java3-2 EchoServer.java3-3 ThreadedEchoServer.java3-4 MailTest.java3-5 InetAddressTest.java3-6 URLConnectionTest.java

3-7 PostTest.java3-8 WeatherApplet.java3-9 ProxySvr.java3-10 proxysvr.c3-11 proxysvr.pl4-1 TestDB.java4-2 ExecSQL.java4-3 QueryDB.java4-4 ViewDB.java5-1 ProductServer.java5-2 ProductImpl.java5-3 Product.java5-4 ShowBindings.java5-5 ProductClient.java5-6 Product.java5-7 Warehouse.java5-8 ProductImpl.java5-9 Customer.java5-10 Warehouse.java5-11 WarehouseImpl.java5-12 WarehouseServer.java5-13 WarehouseClient.java5-14 WarehouseApplet.java5-15 WarehouseApplet.html5-16 ProductImpl.java

5-17 ProductActivator.java5-18 rmid.policy5-19 server.policy5-20 client.policy5-21 EnvClient.java5-22 EnvServer.cpp5-23 SysPropServer.java5-24 SysPropClient.cpp6-1 ListTest.java6-2 LongListTest.java6-3 ListRenderingTest.java6-4 SimpleTree.java6-5 TreeEditTest.java6-6 ClassTree.java6-7 ClassBrowserTest.java6-8 ObjectInspectorTest.java6-9 PlanetTable.java6-10 InvestmentTable.java6-11 ResultSetTable.java6-12 TableSortTest.java6-13 TableCellRenderTest.java6-14 TableSelectionTest.java6-15 EditorPaneTest.java6-16 SplitPaneTest.java6-17 TabbedPaneTest.java

6-18 InternalFrameTest.java7-1 ShapeTest.java7-2 AreaTest.java7-3 StrokeTest.java7-4 PaintTest.java7-5 TransformTest.java7-6 ClipTest.java7-7 CompositeTest.java7-8 RenderQualityTest.java7-9 ImageIOTest.java7-10 MandelbrotTest.java7-11 ImageProcessingTest.java7-12 PrintTest.java7-13 BookTest.java7-14 PrintServiceTest.java7-15 StreamPrintServiceTest.java7-16 TextTransferTest.java7-17 ImageTransferTest.java7-18 LocalTransferTest.java7-19 SerialTransferTest.java7-20 DropTargetTest.java7-21 DragSourceTest.java7-22 SwingDnDTest.java8-1 ImageViewerBean.java8-2 FileNameBean.java

8-3 IntTextBean.java8-4 RangeBean.java8-5 TimerBean.java8-6 TimerListener.java8-7 TimerEvent.java8-8 ChartBean.java8-9 ChartBeanBeanInfo.java8-10 TitlePositionEditor.java8-11 InverseEditor.java8-12 InverseEditorPanel.java8-13 DoubleArrayEditor.java8-14 DoubleArrayEditorPanel.java8-15 ChartBeanBeanInfo.java8-16 ChartBeanCustomizer.java8-17 SpinBean.java8-18 SpinBeanCustomizer.java8-19 SpinBeanBeanInfo.java9-1 ClassLoaderTest.java9-2 Caesar.java9-3 VerifierTest.java9-4 PermissionTest.java9-5 WordCheckPermission.java9-6 SecurityManagerTest.java9-7 WordCheckSecurityManager.java9-8 AuthTest.java

9-9 LineCount.java9-10 AuthTest.policy9-11 jaas.config9-12 MessageDigestTest.java9-13 SignatureTest.java9-14 CertificateSigner.java9-15 FileReadApplet.java9-16 DESTest.java9-17 RSATest.java10-1 NumberFormatTest.java10-2 DateFormatTest.java10-3 CollationTest.java10-4 TextBoundaryTest.java10-5 Retire.java10-6 RetireResources.java10-7 RetireResources de.java10-8 RetireResources zh.java10-9 RetireStrings.properties10-10 RetireStrings de.properties10-11 RetireStrings zh.properties11-1 HelloNative.h11-2 HelloNative.c11-3 HelloNative.java11-4 HelloNativeTest.java11-5 Printf1.java

11-6 Printf1.c11-7 Printf1Test.java11-8 Printf2Test.java11-9 Printf2.java11-10 Printf2.c11-11 EmployeeTest.java11-12 Employee.java11-13 Employee.c11-14 Printf3Test.java11-15 Printf3.java11-16 Printf3.c11-17 Printf4.c11-18 Printf4.java11-19 Printf4Test.java11-20 InvocationTest.c11-21 Win32RegKey.java11-22 Win32RegKey.c11-23 Win32RegKeyTest.java12-1 DOMTreeTest.java12-2 GridBagTest.java12-3 fontdialog.xml12-4 GridBagPane.java12-5 gridbag.dtd12-6 SAXTest.java12-7 XMLWriteTest.java

12-8 TransformTest.java12-9 makehtml.xsl12-10 makeprop.xslFigures1-1 Using a thread to animate a bouncing ball1-2 The Event Dispatch and Ball Threads1-3 Multiple threads1-4 Time-slicing on a single CPU1-5 Thread states1-6 Threads with different priorities1-7 Simultaneous access by two threads1-8 Comparison of unsynchronized and synchronized threads1-9 A deadlock situation1-10 Exception reports in the console1-11 Threads in a Swing program1-12 This file has 36 images of a globe1-13 Picking a frame from a strip of frames1-14 Clock threads1-15 A progress bar1-16 A progress monitor dialog1-17 A progress monitor for an input stream1-18 A sequence of pipes2-1 A queue2-2 Queue implementations2-3 Advancing an iterator

2-4 Removing an element from an array2-5 A doubly linked list2-6 Removing an element from a linked list2-7 Adding an element to a linked list2-8 A hash table2-9 A Linked Hash Table2-10 The interfaces of the collections framework2-11 Classes in the collections framework2-12 Legacy classes in the collections framework2-13 The customized Hello World program3-1 Output of the "time of day" service3-2 A client connecting to a server port3-3 Using telnet to access an HTTP port3-4 Accessing an echo server3-5 Simultaneous access to the threaded echo server3-6 The MailTest program3-7 A network password dialog3-8 An HTML form3-9 Data flow during execution of a CGI script3-10 A web form to request census data3-11 The WeatherReport applet3-12 Applet security disallows connection to a third party3-13 A firewall provides security3-14 Data flow in the weather report applet4-1 JDBC-to-database communication path

4-2 A client/server application4-3 A three-tier application4-4 Sample table containing the HTML books4-5 Two tables joined together4-6 The QueryDB application4-7 A GUI view of a query result4-8 The ViewDB application5-1 Transmitting objects between client and server5-2 Invoking a remote method on a server object5-3 Parameter marshalling5-4 Inheritance diagram5-5 Calling the remote getDescription method5-6 Obtaining product suggestions from the server5-7 Copying local parameter and result objects5-8 Only the ProductImpl methods are remote5-9 BookImpl has additional remote methods5-10 Inheritance of equals and hashCode methods5-11 The warehouse applet6-1 A list box6-2 Choosing from a very long list of selections6-3 A list box with rendered cells6-4 A directory tree6-5 A hierarchy of countries, states, and cities6-6 Tree terminology6-7 Tree classes

6-8 A simple tree6-9 The initial tree display6-10 Collapsed and expanded subtrees6-11 A tree with the Windows look and feel6-12 A tree with no connecting lines6-13 A tree with the horizontal line style6-14 A tree with a root handle6-15 A forest6-16 Leaf icons6-17 Editing a tree6-18 A tree path6-19 The scroll pane scrolls to display a new node6-20 The Default Cell Editor6-21 Tree traversal orders6-22 An inheritance tree6-23 A class browser6-24 An object inspection tree6-25 A simple table6-26 Moving a column6-27 Resizing columns6-28 Growth of an investment6-29 Displaying a query result in a table6-30 Sorting the rows of a table6-31 A table model filter6-32 A table with cell renderers

6-33 A cell editor6-34 Relationship between Table classes6-35 Editing the cell color with a color chooser6-36 Selecting a row6-37 Selecting a range of cells6-38 The editor pane displaying an HTML page6-39 The editor pane in edit mode6-40 A frame with two nested split panes6-41 A tabbed pane6-42 A tabbed pane with scrolling tabs6-43 A multiple document interface application6-44 A Java application with three internal frames6-45 Cascaded internal frames6-46 Tiled internal frames6-47 The user can veto the close property7-1 The rendering pipeline7-2 The bounding rectangle of an ellipse and an arc7-3 Relationships between the shape classes7-4 Constructing a RoundRectangle2D7-5 Constructing an elliptical arc7-6 Arc types7-7 A quadratic curve7-8 A cubic curve7-9 The ShapeTest program7-10 Constructive Area Geometry Operations

7-11 The AreaTest Program7-12 End Cap Styles7-13 Join Styles7-14 A dash pattern7-15 The StrokeTest program7-16 Gradient paint7-17 Texture paint7-18 User and device coordinates7-19 The fundamental transformations7-20 Composing transformations7-21 The TransformTest program7-22 The ClipTest program7-23 Overlaying a partially transparent rectangle on an image7-24 Designing a Composition Rule7-25 Porter-Duff Composition Rules7-26 The CompositeTest program7-27 Antialiasing7-28 The RenderingHints program7-29 An Animated GIF Image7-30 A Mandelbrot set7-31 A rotated image7-32 Blurring an image7-33 Edge detection7-34 A Cross-Platform Print Dialog7-35 Page format measurements

7-36 A Cross-Platform Page Setup Dialog7-37 A Windows print dialog7-38 A Windows page setup dialog7-39 A banner7-40 Printing a page of a banner7-41 A print preview dialog7-42 Viewing a PostScript File7-43 The Attribute Hierarchy7-44 The Attribute Set Hierarchy7-45 The TextTransferTest program7-46 The Windows clipboard viewer after a copy7-47 Copying from a Java program to a native program7-48 Copying from a native program to a Java program7-49 Transferring Local Objects7-50 Data is copied between two instances of a Java application7-51 Initiating a drag operation7-52 Cursor shapes over drop targets7-53 The DropTargetTest program7-54 The DragSourceTest program7-55 The Swing Drag and Drop Test Program8-1 The Properties window in Visual Basic for an image application8-2 A Calendar Bean8-3 Adding a Bean to a Palette in Forte8-4 Building a New Form8-5 The Form Editor Window

8-6 The Code Editor Window8-7 Adding a Bean to a Form8-8 A Property Inspector8-9 Using a property editor to set properties8-10 The ImageViewerBean at work8-11 The Events Tab of the Property Inspector8-12 Event Handling Code in The Edit Window8-13 The range bean8-14 A Veto Message8-15 A Non-visual Bean8-16 Listening to a Custom Event8-17 The chart bean8-18 The property inspector for the chart bean8-19 The TitlePositionEditor at work8-20 A custom editor dialog8-21 The custom editor dialog for editing an array8-22 The customizer for the ChartBean8-23 The spin bean8-24 The customizer of the SpinBean8-25 The SpinBean coupled with an IntTextBean buddy8-26 Bean Contexts8-27 Relationships between the bean context classe8-28 The Message Tracer window9-1 The ClassLoaderTest program9-2 Modifying bytecodes with a hex editor

9-3 Loading a corrupted class file raises a method verification error9-4 A security policy9-5 Permission hierarchy in JDK 1.29-6 Relationship between security classes9-7 The policy tool displaying code sources9-8 The policy tool displaying the permissions for a code source9-9 Editing a permission with the policy tool9-10 The PermissionTest program9-11 The SecurityManagerTest program9-12 Computing a message digest9-13 Public key signature exchange using DSA9-14 Authentication through a trusted intermediary9-15 Authentication through a trusted intermediary's signature9-16 Request for a digital ID9-17 ASN.1 definition of X.509v39-18 The FileReadApplet program9-19 Launching a signed applet10-1 The NumberFormatTest program10-2 The DateFormatTest program running under Chinese Windows10-3 The CollationTest program10-4 The TextBoundaryTest program10-5 The retirement calculator in English10-6 The retirement calculator in German10-7 The retirement calculator in Chinese11-1 The env pointer

11-2 Inheritance hierarchy of array types11-3 The registry editor12-1 The Node interfaces and its subinterfaces12-2 A Simple DOM Tree12-3 A parse tree of an XML document12-4 A font dialog defined by an XML layout12-5 Generating Modern Art12-6 The Apache Batik SVG Viewer12-7 Applying XSL TransformationsPrefaceTo the ReaderAbout This BookConventionsDefinitionsTo the ReaderThe book you have in your hands is the second volume of the fourth edition of Core Java. Thefirst edition appeared in early 1996, the second in late 1996, and the third in 1997/1998. Thefirst two editions appeared in a single volume, but the second edition was already 150 pageslonger than the first, which was itself not a thin book. When we sat down to work on the thirdedition, it became clear that a one-volume treatment of all the features of the Java platformthat a serious programmer needs to know was no longer possible. Hence, we decided to breakup the third edition into two volumes. In the fourth edition, we again organized the material intotwo volumes. However, we rearranged the materials, moving streams into Volume 1 andcollections into Volume 2.The first volume covers the essential features of the language; this volume covers theadvanced topics that a programmer will need to know for professional software development.Thus, as with the first volume and the previous editions of this book, we still are targetingprogrammers who want to put Java technology to work on real projects.Please note: If you are an experienced developer who is comfortable with the new event modeland advanced language features such as inner classes, you need not have read the firstvolume in order to benefit from this volume. (While we do refer to sections of the previous

volume when appropriate and, of course, hope you will buy or have bought Volume 1, you canfind the needed background material in any comprehensive introductory book about the Javaplatform.)Finally, when any book is being written, errors and inaccuracies are inevitable. We would verymuch like to hear about them. Of course, we would prefer to hear about them only once. Forthis reason, we have put up a web site at http://www.horstmann.com/corejava.html with anFAQ, bug fixes, and workarounds. Strategically placed at the end of the bug report web page(to encourage you to read the previous reports) is a form that you can use to report bugs orproblems and to send suggestions for improvements to future editions.About This BookThe chapters in this book are, for the most part, independent of each other. You should beable to delve into whatever topic interests you the most and read the chapters in any order.Chapter 1 covers multithreading, which enables you to program tasks to be done in parallel. (Athread is a flow of control within a program.) We show you how to set up threads and how tomake sure none of them get stuck. We put this knowledge to practical use by example,showing you the techniques needed to build timers and animations.The topic of Chapter 2 is the collections framework of the Java 2 platform. Whenever you wantto collect multiple objects and retrieve them later, you will want to use a collection that is bestsuited for your circumstances, instead of just tossing the elements into a Vector. Thischapter shows you how to take advantage of the standard collections that are prebuilt for youruse.Chapter 3 covers one of the most exciting APIs in the Java platform: the networking API. Javamakes it phenomenally easy to do complex network programming. Not only do we cover thisAPI in depth, we also discuss the important consequences of the applet security model fornetwork programming.Chapter 4 covers JDBC , the Java database connectivity API. We show you how to writeuseful programs to handle realistic database chores, using a core subset of the JDBC API.Please note that this is not a complete treatment of everything you can do with the rich JDBCAPI. (A complete treatment of the JDBC API would require a book almost as long as this one.)Chapter 5 covers remote objects and Remote Method Invocation (RMI). This API lets you workwith Java objects that are distributed over multiple machines. We also show you where therallying cry of "objects everywhere" can realistically be used.Chapter 6 contains all the Swing material that didn't make it into Volume 1, especially theimportant but complex tree and table components. We show the basic uses of editor panesand the Java technology implementation of a "multiple document" interface. Again, we focuson the most useful constructs that you are likely to encounter in practical programming, sincean encyclopedic coverage of the entire Swing library would fill several volumes and would onlybe of interest to dedicated taxonomists.Chapter 7 covers the Java 2D API that you can use to create realistic drawings. The chapter

also covers some advanced features of the Abstract Windowing Toolkit (AWT) that seemedtoo specialized for coverage in Volume 1 but are, nonetheless, techniques that should be partof every programmer's toolkit. These features include printing and the APIs for cut-and-pasteand drag-and-drop. We actually take the cut-and-paste API one step further than SunMicrosystems itself did: We show you how to cut and paste serializable Java objects betweendifferent programs in the Java programming language via the system clipboard.Chapter 8 shows you what you need to know about the component API for the Java platform—JavaBeans . You will see how to write your own beans that other programmers canmanipulate in integrated builder environments. (We do not cover the various builderenvironments that are designed to manipulate beans, however.) The JavaBeans componenttechnology is an extraordinarily important technology for the eventual success of Javatechnology because it can potentially bring the same ease of use to user interfaceprogramming environments that ActiveX controls give to the millions of Visual Basicprogrammers. Of course, since these components are written in the Java programminglanguage, they have the advantage over ActiveX controls in that they are immediately usableacross other platforms and capable of fitting into the sophisticated security model of the Javaplatform.In fact, Chapter 9 takes up that security model. The Java platform was designed from theground up to be secure, and this chapter takes you under the hood to see how this design isimplemented. We show you how to write your own class loaders and security managers forspecial-purpose applications. Then, we take up the new security API that allows for suchimportant features as signed classes.Chapter 10 discusses a specialized feature that we believe can only grow in importance:internationalization. The Java programming language is one of the few languages designedfrom the start to handle Unicode, but the internationalization support in the Java platform goesmuch further. As a result, you can internationalize Java applications so that they not only crossplatforms but cross country boundaries as well. For example, we show you how to write aretirement calculator applet that uses either English, German, or Chinese—depending on thelocale of the browser.Chapter 11 takes up native methods, which let you call methods written for a specific machinesuch as the Microsoft Windows API. Obviously, this feature is controversial: Use nativemethods, and the cross-platform nature of the Java platform vanishes. Nonetheless, everyserious programmer writing Java applications for specific platforms needs to know thesetechniques. There will be times when you need to turn to the operating system's API for yourtarget platform when you are writing a serious application. We illustrate this by showing youhow to access the registry functions in Windows.ConventionsAs is common in many computer books, we use courier type to represent computer code.NOTENotes are tagged with a "notepad" icon that looks like this.

TIPHelpful tips are tagged with this icon.CAUTIONNotes that warn of pitfalls or dangerous situations are tagged with a"Caution" icon.C NOTEThere are a number of C notes that explain the difference between theJava programming language and C .You can skip them if you aren'tinterested in C .The Java platform comes with a large programming library or Application ProgrammingInterface (API). When using an API call for the first time, we add a short summary description,tagged with an API icon. These descriptions are a bit more informal but also a little moreinformative than those in the official on-line API documentation.Programs whose source code is on the CD-ROM are listed as examples, for instance,Example 5-8: WarehouseServer.java refers to the corresponding code on the CD-ROM. Youcan also download these example files from the Web.DefinitionsA Java object is an object that is created by a program that was written in the Javaprogramming language.A Java application is a program that was written in the Java programming language and that islaunched by a Java virtual machine (that is, a virtual machine for the Java platform).AcknowledgmentsWriting a book is always a monumental effort, and rewriting doesn't seem to be much easier,especially with such a rapid rate of change in Java technology. Making a book a reality takesmany dedicated people, and it is my great pleasure to acknowledge the contributions of theentire Core Java team.Our long-suffering editor Greg Doench of Prentice Hall PTR once again did a great job,coordinating all aspects of this complex project. Julie Bettis copyedited the manuscript, with anexcellent eye for consistency and always on the lookout for Teutonic constructions and

violations of the Java trademark rules.Kathi Beste, Bert Stutz, and Marilyn Stutz at Navta Associates, Inc., once again delivered anattractively typeset book. A number of other individuals at Prentice Hall PTR and SunMicrosystems Press also provided valuable assistance, but they managed to stay behind thescenes. I'd like them all to know how much I appreciate their efforts. My thanks also to my coauthor of earlier editions, Gary Cornell, who has since moved on to other ventures.I am very grateful to the excellent reviewing team who found many embarrassing errors andmade lots of thoughtful suggestions for improvement. The new material for this edition wasreviewed by David Geary, Bob Lynch, Paul Philion, and George Thiruvathukal.Reviewers of earlier editions are Alec Beaton (PointBase, Inc.), Joshua Bloch (SunMicrosystems), David Brown, Dr. Nicholas J. De Lillo (Manhattan College), Rakesh Dhoopar(Oracle), Angela Gordon (Sun Microsystems), Dan Gordon (Sun Microsystems), Rob Gordon,Cameron Gregory (olabs.com), Marty Hall (The Johns Hopkins University Applied PhysicsLab), Vincent Hardy (Sun Microsystems), Vladimir Ivanovic (PointBase, Inc.), Jerry Jackson(ChannelPoint Software), Tim Kimmet (Preview Systems), Chris Laffra, Charlie Lai (SunMicrosystems),Doug Langston, Doug Lea (SUNY Oswego), Gregory Longshore, Mark Morrissey (The OregonGraduate Institute), Mahesh Neelakanta (Florida Atlantic University), Blake Ragsdell, StuartReges (University of Arizona), Peter Sanders (ESSI University, Nice, France), Devang Shah(Sun Microsystems), Christopher Taylor, Luke Taylor (Valtech), Kim Topley, Janet Traub,Peter van der Linden (Sun Microsystems), and Burt Walsh.Most importantly, my love, gratitude, and apologies go to my wife Hui-Chen and my childrenTommy and Nina for their continuing support of this never-ending project.Cay HorstmannCupertino, November 2001

CONTENTSChapter 1. MultithreadingzWhat Are Threads?zInterrupting ThreadszThread PropertieszThread PrioritieszSelfish ThreadszSynchronizationzDeadlockszUser Interface Programming with ThreadszUsing Pipes for Communication between ThreadsYou are probably familiar with multitasking: the ability to have more than one program workingat what seems like the same time. For example, you can print while editing or sending a fax. Ofcourse, unless you have a multiple-processor machine, what is really going on is that theoperating system is doling out resources to each program, giving the impression of parallelactivity. This resource distribution is possible because while you may think you are keeping thecomputer busy by, for example, entering data, most of the CPU's time will be idle. (A fast typisttakes around 1/20 of a second per character typed, after all, which is a huge time interval for acomputer.)Multitasking can be done in two ways, depending on whether the operating system interruptsprograms without consulting with them first, or whether pro-grams are only interrupted whenthey are willing to yield control. The former is called preemptive multitasking; the latter is calledcooperative (or, simply, nonpreemptive) multitasking Windows 3.1 and Mac OS 9 arecooperative multitasking systems, and UNIX/Linux, Windows NT (and Windows 95 for 32-bitprograms), and OS X are preemptive. (Although harder to implement, preemptive multitaskingis much more effective. With cooperative multitasking, a badly behaved program can hogeverything.)Multithreaded programs extend the idea of multitasking by taking it one level lower: individualprograms will appear to do multiple tasks at the same time. Each task is usually called athread—which is short for thread of control. Programs that can run more than one thread atonce are said to be multithreaded. Think of each thread as running in a separate context:contexts make it seem as though each thread has its own CPU—with registers, memory, andits own code.So, what is the difference between multiple processes and multiple threads? The essential

difference

An indispensable companion to the best-selling Core Java 2, Vol.I--Fundamentals (0-13- 089468-0), Core Java 2, Volume II: Advanced Features is now available in a revised and expanded fifth edition. It deliver