Tải bản đầy đủ (.pdf) (776 trang)

OReilly java threads 3rd edition sep 2004 ISBN 0596007825

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.46 MB, 776 trang )










TableofContents
Index
Reviews
ReaderReviews
Errata
Academic

JavaThreads,ThirdEdition
ByScottOaks,HenryWong

Publisher :O'Reilly
PubDate :September2004
ISBN :0-596-00782-5
Pages :360


ThreadsareessentialtoJavaprogramming,
butlearningtousethemeffectivelyisa
nontrivialtask.Thisneweditionoftheclassic
JavaThreadsshowsyouhowtotakefull
advantageofJava'sthreadingfacilitiesand
bringsyouup-to-datewiththewatershed


changesinJava2StandardEditionversion
5.0(J2SE5.0).Itprovidesathorough,stepby-stepapproachtothreadsprogramming.











TableofContents
Index
Reviews
ReaderReviews
Errata
Academic

JavaThreads,ThirdEdition
ByScottOaks,HenryWong

Publisher :O'Reilly
PubDate :September2004
ISBN :0-596-00782-5
Pages :360




Copyright

Preface
WhoShouldReadThisBook?

VersionsUsedinThisBook




What'sNewinThisEdition?




ConventionsUsedinThisBook




HowtoContactUs

OrganizationofThisBook
CodeExamples
SafariEnabled

Acknowledgments


Chapter1.IntroductiontoThreads

Section1.1.JavaTerms



Section1.2.AbouttheExamples




Section1.3.WhyThreads?

Section1.4.Summary


Chapter2.ThreadCreationandManagement
Section2.1.WhatIsaThread?




Section2.2.CreatingaThread




Section2.4.TwoApproachestoStoppingaThread





Section2.6.ThreadsandObjects

Section2.3.TheLifecycleofaThread
Section2.5.TheRunnableInterface
Section2.7.Summary


Chapter3.DataSynchronization
Section3.1.TheSynchronizedKeyword

Section3.2.TheVolatileKeyword




Section3.3.MoreonRaceConditions




Section3.5.LockScope




Section3.7.NestedLocks





Section3.9.LockFairness

Section3.4.ExplicitLocking
Section3.6.ChoosingaLockingMechanism
Section3.8.Deadlock
Section3.10.Summary


Chapter4.ThreadNotification
Section4.1.WaitandNotify

Section4.2.ConditionVariables

Section4.3.Summary


Chapter5.MinimalSynchronizationTechniques
Section5.1.CanYouAvoidSynchronization?




Section5.2.AtomicVariables
Section5.3.ThreadLocalVariables

Section5.4.Summary


Chapter6.AdvancedSynchronizationTopics
Section6.1.SynchronizationTerms





Section6.2.SynchronizationClassesAddedinJ2SE5.0




Section6.4.DeadlockDetection

Section6.3.PreventingDeadlock
Section6.5.LockStarvation

Section6.6.Summary


Chapter7.ThreadsandSwing
Section7.1.SwingThreadingRestrictions



Section7.2.ProcessingontheEvent-DispatchingThread






Section7.3.UsinginvokeLater()andinvokeAndWait()

Section7.4.Long-RunningEventCallbacks

Section7.5.Summary


Chapter8.ThreadsandCollectionClasses
Section8.1.OverviewofCollectionClasses




Section8.2.SynchronizationandCollectionClasses




Section8.4.UsingtheCollectionClasses

Section8.3.TheProducer/ConsumerPattern
Section8.5.Summary


Chapter9.ThreadScheduling
Section9.1.AnOverviewofThreadScheduling

Section9.2.SchedulingwithThreadPriorities





Section9.3.PopularThreadingImplementations
Section9.4.Summary


Chapter10.ThreadPools
Section10.1.WhyThreadPools?

Section10.2.Executors




Section10.3.UsingaThreadPool




Section10.5.ThreadCreation




Section10.7.Single-ThreadedAccess

Section10.4.QueuesandSizes
Section10.6.CallableTasksandFutureResults
Section10.8.Summary


Chapter11.TaskScheduling

Section11.1.OverviewofTaskScheduling

Section11.2.Thejava.util.TimerClass




Section11.3.Thejavax.swing.TimerClass
Section11.4.TheScheduledThreadPoolExecutorClass

Section11.5.Summary


Chapter12.ThreadsandI/O
Section12.1.ATraditionalI/OServer




Section12.2.ANewI/OServer
Section12.3.InterruptedI/O

Section12.4.Summary


Chapter13.MiscellaneousThreadTopics
Section13.1.ThreadGroups





Section13.2.ThreadsandJavaSecurity



Section13.4.ThreadsandClassLoading

Section13.3.DaemonThreads





Section13.5.ThreadsandExceptionHandling




Section13.6.Threads,Stacks,andMemoryUsage
Section13.7.Summary


Chapter14.ThreadPerformance
Section14.1.OverviewofPerformance

Section14.2.SynchronizedCollections





Section14.3.AtomicVariablesandContendedSynchronization
Section14.4.ThreadCreationandThreadPools

Section14.5.Summary


Chapter15.ParallelizingLoopsforMultiprocessorMachines
Section15.1.ParallelizingaSingle-ThreadedProgram




Section15.2.MultiprocessorScaling
Section15.3.Summary


AppendixA.SupersededThreadingUtilities
SectionA.1.TheBusyFlagClass

SectionA.2.TheCondVarClass




SectionA.3.TheBarrierClass




SectionA.5.TheThreadPoolClass


SectionA.4.TheRWLockClass
SectionA.6.TheJobSchedulerClass

SectionA.7.Summary


Colophon

Index


Copyright©2004O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
JavaThreads,theimageofamarineinvertebrate,andrelated
tradedressaretrademarksofO'ReillyMedia,Inc.
JavaandallJava-basedtrademarksandlogosaretrademarks
orregisteredtrademarksofSunMicrosystems,Inc.,inthe
UnitedStatesandothercountries.O'ReillyMedia,Inc.is
independentofSunMicrosystems,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto

distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
WhenSunMicrosystemsreleasedthealphaversionofJava©in
thewinterof1995,developersallovertheworldtooknotice.
ThereweremanyfeaturesofJavathatattractedthese
developers,nottheleastofwhichwerethesetofbuzzwords
Sunusedtopromotethelanguage.Javawas,amongother
things,robust,safe,architecture-neutral,portable,objectoriented,simple,andmultithreaded.Formanydevelopers,
theselasttwobuzzwordsseemedcontradictory:howcoulda
languagethatismultithreadedbesimple?
ItturnsoutthatJava'sthreadingsystemissimple,atleast
relativetootherthreadingsystems.Thissimplicitymakes
Java'sthreadingsystemeasytolearnsothatevendevelopers
whoareunfamiliarwiththreadscanpickupthebasicsofthread
programmingwithrelativeease.
InearlyversionsofJava,thissimplicitycamewithtradeoffs;
someoftheadvancedfeaturesthatarefoundinother
threadingsystemswerenotavailableinJava.Java2Standard
EditionVersion5.0(J2SE5.0)changesallofthat;itprovidesa
largenumberofnewthread-relatedclassesthatmakethetask
ofwritingmultithreadedprogramsthatmucheasier.

Still,programmingwiththreadsremainsacomplextask.This
bookshowsyouhowtousethethreadingtoolsinJavato
performthebasictasksofthreadedprogrammingandhowto
extendthemtoperformmoreadvancedtasksformorecomplex
programs.


WhoShouldReadThisBook?
Thisbookisintendedforprogrammersofalllevelswhoneedto
learntousethreadswithinJavaprograms.Thisincludes
developerswhohavepreviouslyusedJavaandwrittenthreaded
programs;J2SE5.0includesawealthofnewthread-related
classesandfeatures.Therefore,evenifyou'vewrittena
threadedprograminJava,thisbookcanhelpyoutoexploitnew
featuresofJavatowriteevenmoreeffectiveprograms.
Thefirstfewchaptersofthebookdealwiththeissuesof
threadedprogramminginJava,startingatabasiclevel;no
assumptionismadethatthedeveloperhashadanyexperience
inthreadedprogramming.Asthechaptersprogress,the
materialbecomesmoreadvanced,intermsofboththe
informationpresentedandtheexperienceofthedeveloperthat
thematerialassumes.Fordeveloperswhoarenewtothreaded
programming,thissequenceshouldprovideanatural
progressionofthetopic.
Thisbookisideallysuitedtodeveloperstargetingthesecond
waveofJavaprogramsmorecomplexprogramsthatfullyexploit
thepowerofJava'sthreadingsystem.Wemaketheassumption
thatreadersofthebookarefamiliarwithJava'ssyntaxand
features.Inafewareas,wepresentcomplexprogramsthat
dependonknowledgeofotherJavafeatures:AWT,Swing,NIO,

andsoon.However,thebasicprincipleswepresentshouldbe
understandablebyanyonewithabasicknowledgeofJava.
We'vefoundthatbooksthatdealwiththeseotherAPIstendto
giveshortshrifttohowmultiplethreadscanfullyutilizethese
featuresofJava(thoughdoubtlessthereverseistrue;wemake
noattempttoexplainnonthread-relatedJavaAPIs).
Thoughthematerialpresentedinthisbookdoesnotassume
anypriorknowledgeofthreads,itdoesassumethatthereader
hasknowledgeofotherareasoftheJavaAPIandcanwrite


simpleJavaprograms.


VersionsUsedinThisBook
WritingabookonJavaintheageofInternettimeishardthe
sandonwhichwe'restandingisconstantlyshifting.Butwe've
drawnalineinthatsand,andthelinewe'vedrawnisatthe
Java2StandardEdition(J2SE)Version5.0fromSun
Microsystems.ThissoftwarewaspreviouslyknownasJ2SE
Version1.5.
It'slikelythatversionsofJavathatpostdatethisversionwill
containsomechangestothethreadingsystemnotdiscussedin
thiseditionofthebook.Wewillalsopointoutthedifferences
betweenJ2SE5.0andpreviousversionsofJavaaswegoso
thatdevelopersusingearlierreleasesofJavawillalsobeableto
usethisbook.
MostofthenewthreadingfeaturesinJ2SE5.0areavailable
(withdifferentAPIs)fromthird-partiesforearlierversionsof
Java(includingclasseswedevelopedinearliereditionsofthis

book).Therefore,evenifyou'renotusingJ2SE5.0,you'llget
fullbenefitfromthetopicscoveredinthisbook.


What'sNewinThisEdition?
ThiseditionincludesinformationaboutJ2SE5.0.Oneofthe
mostsignificantchangesinJ2SE5.0istheinclusionofJava
SpecificationRequest(JSR)166,oftenreferredtoasthe
"concurrencyutilities."JSR-166specifiesanumberofthreadrelatedenhancementstoexistingAPIsaswellasprovidinga
largepackageofnewAPIs.
ThesenewAPIsinclude:

Atomicvariables
Asetofclassesthatprovidethreadsafeoperationswithout
synchronization

Explicitlocks
Synchronizationlocksthatcanbeacquiredandreleased
programmatically

Conditionvariables
Variablesthatcanbethesubjectofatargetednotification
whencertainconditionsexist

Queues
Collectionclassesthatarethread-aware


Synchronizationprimitives
Newclassesthatperformcomplextypesofsynchronization


Threadpools
Classesthatcanmanageapoolofthreadstoruncertain
tasks

Threadschedulers
Classesthatcanexecutetasksataparticularpointintime
We'vefullyintegratedthenewfeaturesofJ2SE5.0throughout
thetextofthisedition.Thenewfeaturescanbesplitintothree
categories:

Newimplementationsofexistingfeatures
TheJavalanguagehasalwayshadthecapabilitytoperform
datasynchronizationandthreadnotification.However,
implementationofthesefeatureswassomewhatlimited;
youcould,forexample,synchronizeblocksofcodeorentire
methodsbutsynchronizingacrossmethodsandclasses
requiredextraprogramming.InJ2SE5.0,explicitlocksand
conditionvariablesallowyoumoreflexibilitywhenusing
thesefeatures.
Thesenewimplementationsdonotintroducenewconcepts
foradeveloper.Adeveloperwhowantstowritea
threadsafeprogrammustensurethatherdataiscorrectly


synchronized,whethersheusesJ2SE5.0'sexplicitlocksor
themorebasicsynchronizedkeyword.Therefore,bothare
presentedtogetherwhenwetalkaboutdata
synchronization.Thesameistrueofconditionvariables,
whichprovidethreadnotificationandarediscussed

alongsideJava'swait()andnotify()methods,andof
queues,whicharediscussedalongwithJava'sother
collectionclasses.

Importantthreadutilities
Atsomepointintime,virtuallyalldeveloperswhowrite
threadedprogramswillneedtousebasicthreadutilities
suchasapoolorascheduler;manyofthemwillalsoneed
touseadvancedsynchronizationprimitives.Arecognitionof
thisfactisonethingthatdroveJSR-166itwascertainly
possibleinpreviousversionsofJavatodevelopyourown
threadpoolsandschedulers.Butgiventheimportanceof
threadingintheJavaplatform,addingthesebasicutilities
greatlyincreasesprogrammerproductivity.

Minimalsynchronizationutilities
Java'snewatomicclassesprovideameansbywhich
developerscan,whennecessary,writeapplicationsthat
avoidsynchronization.Thiscanleadtoprogramsthatare
highlyconcurrent.
Ifyou'vereadpreviouseditionsofthisbook,theconcepts
presentedinthefirsttwocategorieswillbefamiliar.Inprevious
editions,wedevelopedourowndatasynchronizationclasses,
threadpools,andsoon.Inthoseeditions,weexplainedin
detailhowourimplementationsworkedandthenusedthemin
severalexamples.Inthisedition,wefocussolelyonhowtouse


theseclasseseffectively.
Theinformationthatfallsintothethirdcategoryiscompletely

newtothisedition.Theclassesthatperformminimal
synchronizationrequirenewsupportfromthevirtualmachine
itselfandcouldnotbedevelopedindependentofthosechanges.


OrganizationofThisBook
Here'sanoutlineofthebook,whichincludes15chaptersand1
appendix:

Chapter1
Thischapterformsabasicintroductiontothetopicof
threads:whytheyareusefulandourapproachto
discussingthem.

Chapter2
Thischaptershowsyouhowtocreatethreadsandrunnable
objectswhileexplainingthebasicprinciplesofhowthreads
work.

Chapter3
Thischapterdiscussesthebasiclevelatwhichthreads
sharedatasafelycoordinatingwhichthreadisallowedto
accessdataatanytime.Sharingdatabetweenthreadsis
theunderlyingtopicofournextfourchapters.

Chapter4
Thischapterdiscussesthebasictechniquethreadsuseto
communicatewitheachotherwhentheyhavechanged
data.Thisallowsthreadstorespondtodatachanges



insteadofpollingforsuchchanges.

Chapter5
Thischapterdiscussesclassesandprogrammingmethods
thatachievedatasafetywhileusingaminimalamountof
synchronization.

Chapter6
Inthischapter,wecompleteourexaminationofdata
sharingandsynchronizationwithanexaminationof
deadlock,starvation,andmiscellaneouslockingclasses.

Chapter7
Swingclassesarenotthreadsafe.Thischapterdiscusses
howmultithreadedprogramscantakefulladvantageof
Swing.

Chapter8
Javacollectionclassesarewrittenforavarietyof
circumstances.Somearethreadsafeandsomearenot,and
J2SE5.0introducesnewcollectionclassesforuse
specificallywiththreadutilities.Wesortallthatoutinthis
chapter.

Chapter9


SchedulingistheprocesswherebyasingleCPUselectsa
threadtorun.Threadschedulingismoreapropertyofan

operatingsystem(OS)thanaJavaprogram,andthis
chapterdiscussestherelationshipbetweenthevirtual
machineandtheOSinthisarea.

Chapter10
Thischapterdiscussesthreadpoolsacollectionofthreads
thatcanbeusedtorunarbitrarytasks.Weusethethread
poolimplementationofJ2SE5.0fordiscussionofthe
generalprinciplesofusingthreadpools.

Chapter11
Taskschedulersexecuteataskoneormoretimesatsome
pointinthefuture.Thissetofclassesincludestimers(Java
hashadtimerclassessinceJDK1.3)andageneraltask
scheduleravailableinJ2SE5.0.

Chapter12
DealingwithI/Oisoneoftheprimaryreasonswhy
developersusethreadsinJava.Inthischapter,weuseallof
Java'sthreadingfeaturestoshowyouhowtohandleI/O
effectivelyinmultithreadedprograms.

Chapter13
Inthischapter,wecompleteourexaminationofthreadrelatedfeaturesofJavabyexaminingthreadsecurity,


threadgroups,threadstacks,andothertopics.

Chapter14
Performanceofthread-relatedfeaturesandparticularly

synchronizationconstructsiskeytowritingmultithreaded
programs.Inthischapter,wetestvariouslow-level
programmingfeaturesandexploresometruthsandmyths
aboutthreadperformance.

Chapter15
Inthischapter,weshowaprocessforexploitingthepower
ofmultiprocessormachinestocalculateCPU-intensiveloops
inparallel.

AppendixA
J2SE5.0introducesanumberofthread-relatedclasses.
Manyoftheseclassesaresimilartoclassesdevelopedin
previouseditionsofthisbook;welistthoseclassesinthis
appendixasanaidtodeveloperswhocannotyetupgradeto
J2SE5.0.


ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:

Italic
IndicatesURLsandfilenames,andisusedtointroducenew
terms.Sometimesweexplainthreadfeaturesusinga
question-and-answerformat.Questionsposedbythereader
arerenderedinitalic.

Constantwidth
Indicatescodeexamples,methods,variables,parameters,
andkeywordswithinthetext.


Constantwidthbold
Indicatesuserinput,suchascommandsthatyoutypeon
thecommandline.


CodeExamples
Allexamplespresentedinthebookarecomplete,running
applications.However,manyoftheprogramlistingsare
shortenedbecauseofspaceandreadabilityconsiderations.The
fullexamplesmayberetrievedonlinefrom
/>Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"JavaThreads,ThirdEdition,byScottOaksandHenry
Wong.Copyright2004O'ReillyMedia,0-596-00782-5."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat




HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
O'Reillymaintainsawebpageforthisbook,wherewelist
errata,examples,andanyadditionalinformation.Youcan
accessthispageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

FormoreinformationaboutO'Reillybooks,conferences,
ResourceCenters,andtheO'ReillyNetwork,seeourwebsite
at:



SafariEnabled

WhenyouseetheSafari®Enabledicononthebackcoverof
yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechnology

books,cutandpastecodesamples,downloadchapters,and
findquickanswerswhenyouneedthemostaccurate,current
information.
Tryitforfreeat.


Acknowledgments
Asreadersofprefacesarewellaware,writingabookisnever
aneffortundertakensolelybytheauthorswhogetallthecredit
onthecover.Wearedeeplyindebtedtothefollowingpeoplefor
theirhelpandencouragement:MichaelLoukides,whobelieved
uswhenwesaidthatthiswasanimportanttopicandwho
shepherdedusthroughthecreativeprocess;DavidFlanagan,
forvaluablefeedbackonthedrafts;DebCameron,forediting
sometimesramblingtextintocoherency;HongZhang,for
helpinguswithWindowsthreadingissues;andReynold
Jabbour,WendyTalmont,SteveWilson,andTimCramerfor
supportingusinourworkoverthepastsixyears.
Mostly,wemustthankourrespectivefamilies.ToJames,who
gaveScottthesupportandencouragementnecessarytosee
thisbookthrough(andtocopewithhiscontinualstateof
distraction),andtoNini,whoknewtoleaveHenryaloneforthe
tenpercentofthetimewhenhewascreative,andencouraged
himtherestofthetimethankyouforeverything!
Finally,wemustthankthemanyreadersoftheearliereditions
ofthisbookwhosentusinvaluablefeedback.Wehavetriedour
besttoanswereveryconcernthattheyhaveraised.Keepthose
cardsandletterscoming!



Chapter1.IntroductiontoThreads
ThisisabookaboutusingthreadsintheJavaprogramming
languageandtheJavavirtualmachine.Thetopicofthreadsis
veryimportantinJavasoimportantthatmanyfeaturesofthe
threadingsystemarebuiltintotheJavalanguageitselfwhile
otherfeaturesofthethreadingsystemarerequiredbytheJava
virtualmachine.ThreadingisanintegralpartofusingJava.
Theconceptofthreadsisnotanewone:forsometime,many
operatingsystemshavehadlibrariesthatprovidetheC
programmeramechanismtocreatethreads.Otherlanguages,
suchasAda,havesupportforthreadsembeddedintothe
language,muchassupportforthreadsisbuiltintotheJava
language.Nonetheless,untilJavacamealong,thetopicof
threadswasusuallyconsideredaperipheralprogrammingtopic,
onethatwasonlyneededinspecialprogrammingcases.
WithJava,thingsaredifferent:itisimpossibletowriteanybut
thesimplestJavaprogramwithoutintroducingthetopicof
threads.AndthepopularityofJavaensuresthatmany
developers,whomightneverhaveconsideredlearningabout
threadingpossibilitiesinalanguagesuchasCorC++,needto
becomefluentinthreadedprogramming.
Futhermore,theJavaplatformhasmaturedthroughoutthe
years.InJava2StandardEditionVersion5.0(J2SE5.0),the
classesavailableforthread-relatedprogrammingrivalmany
professionalthreadingpackages,mitigatingtheneedtouseany
commerciallibrary(aswassomewhatcommoninprevious
releasesofJava).SoJavadevelopersnotonlyneedtobecome
knowledgeableinthreadedprogrammingtowritebasic
applicationsbutwillwanttolearnthecomplete,richsetof
classesavailableforwritingcomplex,commercial-grade

applications.


1.1JavaTerms
Let'sstartbydefiningsometermsusedthroughoutthisbook.
ManyJava-relatedtermsareusedinconsistentlyinvarious
sources;weendeavortobeconsistentinourusageofthese
termsthroughoutthebook.

Java
First,isthetermJavaitself.Asyouknow,Javastartedout
asaprogramminglanguage,andmanypeopletodaystill
thinkofJavaasbeingsimplyaprogramminglanguage.But
Javaismuchmorethanjustaprogramminglanguage:it's
alsoanAPIspecificationandavirtualmachinespecification.
SowhenwesayJava,wemeantheentireJavaplatform:
theprogramminglanguage,itsAPIs,andavirtualmachine
specificationthat,takentogether,defineanentire
programmingandruntimeenvironment.Oftenwhenwesay
Java,it'sclearfromthecontextthatwe'retalking
specificallyabouttheprogramminglanguage,orpartsof
theJavaAPI,orthevirtualmachine.Thepointtoremember
isthatthethreadingfeatureswediscussinthisbookderive
theirpropertiesfromallthecomponentsoftheJava
platformtakenasawhole.Whileit'spossibletotakethe
Javaprogramminglanguage,directlycompileitinto
assemblycode,andrunitoutsideofthevirtualmachine,
suchanexecutablemaynotnecessarilybehavethesame
astheprogramswedescribeinthisbook.


Virtualmachine,interpreters,andbrowsers
TheJavavirtualmachineisthecodethatactuallyrunsa


×