




已阅读5页,还剩9页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
外文原文One:AjaxforJavadevelopers:JavaobjectserializationforAjaxIfyouredoingJavaWebdevelopmentusingAsynchronousJavaScriptandXML(Ajax),thendeliveringdatafromtheservertotheclientisprobablyyourtopconcern.InthissecondarticleintheAjaxforJavadevelopersseries,PhilipMcCarthywalksyouthroughfiveapproachestoJavaobjectserializationandgivesyoualltheinformationyouneedtochoosethedataformatandtechnologybestsuitedtoyourapplication.Inthefirstarticlinthisseries,IintroducedyoutothebuildingblocksofAjax:(1)、HowtouseaJavaScriptXMLHttpRequestobjecttosendanasynchronousrequesttoaserverfromaWebpage(2)、HowtohandleandrespondtothatrequestwithaJavaservletreturninganXMLdocumenttotheclient(3)、HowtousethatresponsedocumentontheclienttoupdateyourpageviewThistime,IllcontinuediscussingthedevelopmentfundamentalsofAjax,butImfocusingonwhatmattersmostformanyJavaWebdevelopers:producingdatafortheclient.MostJavadevelopershaveappliedtheModel-View-Controller(MVC)patterntotheirWebapplications.InatraditionalWebapplication,theviewcomponentiscomposedofJSPs,orperhapsanotherpresentationtechnologysuchasVelocitytemplates.ThesepresentationcomponentsupdatetheuserinterfacebydynamicallyproducingawholenewpageofHTMLtoreplacewhattheuserwaspreviouslylookingat.InthecaseofaJavaWebapplicationwithanAjaxUI,however,theJavaScriptclientcodehasultimateresponsibilityforupdatingwhattheusersees,basedondatareceivedinresponsetoanXMLHttpRequest.Fromtheperspectiveoftheserver,theviewbecomesthedatarepresentationitsendsinresponsetoclientrequests.ProducingXMLfromJavaclassesThereareplentyofreasonstodeliverAjaxresponsesasXML:everyAjax-capablebrowserhasmethodsfornavigatingXMLdocuments,andtherearemanyserver-sidetechnologiesforworkingwithXMLdata.ItseasytodefinethecontractbetweenyourAjaxclientandserverbyproducingaschematodescribethetypesofdocumentsthatwillbeexchanged,andifyoutakeaservice-orientedapproachtoyourserver-sidearchitecture,usingXMLallowsnon-Ajaxclientstoconsumeyourdatafeedsaswell.IllconsiderthreeofthewaysyoucanproduceXMLdatafromyourJavaobjectsanddiscusstheprosandconsofeach.Roll-your-ownserializationFirstofall,youcouldgenerateXMLprogramaticallyfromyourobjectgraph.ThisapproachcanbeassimpleasimplementingatoXml()methodineachofyourJavaBeanclasses.YouwouldthenpickasuitableXMLAPIandhaveeachbeanemitelementstorepresentitsstateandrecursivelycalldowntheobjectgraphtoitsmembers.Clearly,thisapproachdoesntscalewelltoalargenumberofclassesbecauseeachoneneedstohaveitsownXML-generatingcodespeciallywritten.Ontheupside,itsasimpleapproachtoimplement,theresnooverheadintermsofextraconfigurationoramore-complexbuildprocess,andanygraphcomposedofyourJavaBeanscanbeturnedintoanXMLdocumentwithacoupleofcalls.XMLbindingframeworksInrecentyears,severalJavaAPIshavebeendevelopedtosimplifytheprocessofbindingXMLdocumentstoJavaobjectgraphrepresentations.MostprovidebothXMLmarshalingandunmarshaling;thatis,theyperformtwo-wayconversionsbetweenJavaobjectgraphsandXML.TheseframeworksencapsulatealltheworkofhandlingXML,meaningthatapplicationcodeonlyhastodealwithplainJavaobjects.Theytendtoprovideusefulancillaryfunctionsaswell,suchasdocumentvalidation.Broadly,theseframeworkstaketwodifferentapproaches:codegenerationandobject-to-XMLmapping.Illexplainboth.Thecode-generationapproachBindingframeworksthatemploycodegenerationincludeXMLBeans,JAXB,Zeus,andJBind.Castorcanalsoemploythistechnique.ThestartingpointforanyoftheseframeworksisanXMLschemathatdescribesthedatatypesofyourdocuments.Usingtoolsprovidedbytheframework,youthengenerateJavaclassesthatrepresenttheseschema-definedtypes.Finally,youwriteyourapplicationusingthesegeneratedclassestorepresentyourmodeldataandserializethemtoXMLthroughsomeconvenientmechanismprovidedbytheframework.ThecodegenerationapproachisagoodoneifyourapplicationemploysalargeXMLgrammar.ThescalingproblemofwritingcustomXML-serializationmethodsacrosstensofclassesvanishes.Ontheotherhand,younolongergettodefineyourownJavaBeans.Theframework-generatedJavaclassestypicallyfollowtheXMLsstructuresveryclosely,whichcanresultinthembeingratherunwieldytocodeagainst.Also,thegeneratedclassesbecomedumbdatacontainersbecauseyoucantgenerallyaddbehaviortothem.Broadlyspeaking,youneedtomakecompromisesinyourapplicationcodetoplaynicelywiththeschema-generatedtypes.Anotherpitfallisthatachangeintheschemacauseschangestothegeneratedclasses,whichinturnhasaknock-oneffecttoanycodeyouvewrittenaroundthem.XMLbindingframeworksofthistypearemostusefulindataunmarshaling(i.e.,consumingXMLdocumentsandconvertingthemintoJavaobjects).Unlessyouhaveahugedatamodelandwouldbenefitfromhavingclassesgeneratedforyou,code-generation-basedframeworksareprobablyoverkillforanAjaxapplication.ThemappingapproachFrameworksthatemploymappingincludeCastorandApacheCommonsBetwixt.Mappingisgenerallyamoreflexibleandlightweightsolutionthancodegeneration.First,youcodeyourJavaBeansasyouusuallywould,includinganybehaviorandwhateverconveniencemethodsyoulike.Then,atruntime,youcallontheframeworksintrospection-basedmarshaler,anditproducesanXMLdocumentbasedonthetypes,names,andvaluesofyourobjectsmembers.Bydefiningmappingfilesforyourclasses,youcanoverridethedefaultbindingstrategyandadvisethemarshalerhowyoudlikeyourclassestoberepresentedinXML.Thisapproachisagoodcompromisebetweenscalabilityandflexibility.YougettowriteyourJavaclassesthewayyoulikethem,andthemarshalersavesyoufromdealingwithXML.However,althoughthemappingdefinitionfilesaresimpletowriteandscalereasonablywell,themappingrulescanonlychangethestandardbindingbehaviorsomuch,andsomedegreeofcouplingbetweenthestructureofyourobjectsandtheirXMLrepresentationwillalwaysremain.Ultimately,youmayhavetocompromiseeitheryourJavarepresentationsoryourXMLformatforthemappingapproachtowork.DatabindingsummaryDennisSosnoskihaswrittenindepthonthesubjectofXMLdatabindingAPIsofboththecode-generationandcode-mappingflavors.IdrecommendhisexcellentarticlesonCastorandonthecode-generationframeworksifyouwanttoinvestigatethisareafurtherOnthewhole,thecode-generationapproachtradesofftoomuchflexibilityandconveniencetobeusefulforthetypicalAjaxapplication.Ontheotherhand,themapping-basedframeworksmayserveyouwell,aslongasyoucantailortheirmappingstrategiesenoughtoproducetheXMLyouwantfromyourobjects.AlloftheXMLbindingAPIsshareamajordrawbackwiththemanualserializationtechnique:thecouplingofmodelandview.BeinglimitedtoasingleXMLrepresentationofeachobjecttypemeansitislikelythattherewillalwaysbesomeredundantdatatravelingacrossthenetwork.Amoreseriousproblemisthattheclientcodecannotobtainaspecializedviewwhenthesituationdemandsitandmayhaveanawkwardtimetryingtodealwiththecompromisedone-size-fits-allviewofagivenobjectgraph.IntraditionalWebapplicationdevelopment,pagetemplatingsystemsareusedtocleanlyseparateviewgenerationfromcontrollerlogicandmodeldata.ItsanapproachthatcanhelpinanAjaxscenarioaswell.Two:MultipleThreadsObjectsprovideawaytodivideaprogramintoindependentsections.Often,youalsoneedtoturnaprogramintoseparate,independentlyrunningsubtasks.Eachoftheseindependentsubtasksiscalledathread,andyouprogramasifeachthreadrunsbyitselfandhastheCPUtoitself.SomeunderlyingmechanismisactuallydividinguptheCPUtimeforyou,butingeneral,youdonthavetothinkaboutit,whichmakesprogrammingwithmultiplethreadsamucheasiertask.Aprocessisaself-containedrunningprogramwithitsownaddressspace.Amultitaskingoperatingsystemiscapableofrunningmorethanoneprocess(program)atatime,whilemakingitlooklikeeachoneischuggingalongonitsown,byperiodicallyprovidingCPUcyclestoeachprocess.Athreadisasinglesequentialflowofcontrolwithinaprocess.Asingleprocesscanthushavemultipleconcurrentlyexecutingthreads.Therearemanypossibleusesformultithreading,butingeneral,youllhavesomepartofyourprogramtiedtoaparticulareventorresource,andyoudontwanttohanguptherestofyourprogrambecauseofthat.Soyoucreateathreadassociatedwiththateventorresourceandletitrunindependentlyofthemainprogram.Agoodexampleisa“quit”buttonyoudontwanttobeforcedtopollthequitbuttonineverypieceofcodeyouwriteinyourprogramandyetyouwantthequitbuttontoberesponsive,asifyouwerecheckingitregularly.Infact,oneofthemostimmediatelycompellingreasonsformultithreadingistoproducearesponsiveuserinterface.InheritingfromThreadThesimplestwaytocreateathreadistoinheritfromclassThread,whichhasallthewiringnecessarytocreateandrunthreads.ThemostimportantmethodforThreadisrun(),whichyoumustoverridetomakethethreaddoyourbidding.Thus,run()isthecodethatwillbeexecuted“simultaneously”withtheotherthreadsinaprogram.Thefollowingexamplecreatesanynumberofthreadsthatitkeepstrackofbyassigningeachthreadauniquenumber,generatedwithastaticvariable.TheThreadsrun()methodisoverriddentocountdowneachtimeitpassesthroughitsloopandtofinishwhenthecountiszero(atthepointwhenrun()returns,thethreadisterminated)./:c14:SimpleThread.java/VerysimpleThreadingexample.publicclassSimpleThreadextendsThreadprivateintcountDown=5;privatestaticintthreadCount=0;privateintthreadNumber=+threadCount;publicSimpleThread()System.out.println(Making+threadNumber);publicvoidrun()while(true)System.out.println(Thread+threadNumber+(+countDown+);if(-countDown=0)return;publicstaticvoidmain(Stringargs)for(inti=0;i5;i+)newSimpleThread().start();System.out.println(AllThreadsStarted);Arun()methodvirtuallyalwayshassomekindofloopthatcontinuesuntilthethreadisnolongernecessary,soyoumustestablishtheconditiononwhichtobreakoutofthisloop(or,inthecaseabove,simplyreturnfromrun().Often,run()iscastintheformofaninfiniteloop,whichmeansthat,barringsomeexternalfactorthatcausesrun()toterminate,itwillcontinueforever.Inmain()youcanseeanumberofthreadsbeingcreatedandrun.Thestart()methodintheThreadclassperformsspecialinitializationforthethreadandthencallsrun().Sothestepsare:theconstructoriscalledtobuildtheobject,thenstart()configuresthethreadandcallsrun().Ifyoudontcallstart()(whichyoucandointheconstructor,ifthatsappropriate)thethreadwillneverbestarted.SharinglimitedresourcesYoucanthinkofasingle-threadedprogramasonelonelyentitymovingaroundthroughyourproblemspaceanddoingonethingatatime.Becausetheresonlyoneentity,youneverhavetothinkabouttheproblemoftwoentitiestryingtousethesameresourceatthesametime,liketwopeopletryingtoparkinthesamespace,walkthroughadooratthesametime,oreventalkatthesametime.Withmultithreading,thingsarentlonelyanymore,butyounowhavethepossibilityoftwoormorethreadstryingtousethesamelimitedresourceatonce.Collidingoveraresourcemustbepreventedorelseyoullhavetwothreadstryingtoaccessthesamebankaccountatthesametime,printtothesameprinter,oradjustthesamevalve,etc.ImproperlyaccessingresourcesConsideravariationonthecountersthathavebeenusedsofarinthischapter.Inthefollowingexample,eachthreadcontainstwocountersthatareincrementedanddisplayedinsiderun().Inaddition,theresanotherthreadofclassWatcherthatiswatchingthecounterstoseeiftheyrealwaysequivalent.Thisseemslikeaneedlessactivity,sincelookingatthecodeitappearsobviousthatthecounterswillalwaysbethesame.Butthatswherethesurprisecomesin.HowJavasharesresourcesJavahasbuilt-insupporttopreventcollisionsoveronekindofresource:thememoryinanobject.Sinceyoutypicallymakethedataelementsofaclassprivateandaccessthatmemoryonlythroughmethods,youcanpreventcollisionsbymakingaparticularmethodsynchronized.Onlyonethreadatatimecancallasynchronizedmethodforaparticularobject(althoughthatthreadcancallmorethanoneoftheobjectssynchronizedmethods).Herearesimplesynchronizedmethods:synchronizedvoidf()/*.*/synchronizedvoidg()/*.*/Eachobjectcontainsasinglelock(alsocalledamonitor)thatisautomaticallypartoftheobject(youdonthavetowriteanyspecialcode).Whenyoucallanysynchronizedmethod,thatobjectislockedandnoothersynchronizedmethodofthatobjectcanbecalleduntilthefirstonefinishesandreleasesthelock.Intheexampleabove,iff()iscalledforanobject,g()cannotbecalledforthesameobjectuntilf()iscompletedandreleasesthelock.Thus,theresasinglelockthatssharedbyallthesynchronizedmethodsofaparticularobject,andthislockpreventscommonmemoryfrombeingwrittenbymorethanonemethodatatime(i.e.,morethanonethreadatatime).Theresalsoasinglelockperclass(aspartoftheClassobjectfortheclass),sothatsynchronizedstaticmethodscanlockeachotheroutfromsimultaneousaccessofstaticdataonaclass-widebasis.Notethatifyouwanttoguardsomeotherresourcefromsimultaneousaccessbymultiplethreads,youcandosobyforcingaccesstothatresourcethroughsynchronizedmethods.BlockingAthreadcanbeinanyoneoffourstates:New:Thethreadobjecthasbeencreatedbutithasntbeenstartedyetsoitcannotrun.Runnable:Thismeansthatathreadcanberunwhenthetime-slicingmechanismhasCPUcyclesavailableforthethread.Thus,thethreadmightormightnotberunning,buttheresnothingtopreventitfrombeingruniftheschedulercanarrangeit;itsnotdeadorblocked.Dead:Thenormalwayforathreadtodieisbyreturningfromitsrun()method.Youcanalsocallstop(),butthisthrowsanexceptionthatsasubclassofError(whichmeansyouarentforcedtoputthecallinatryblock).Rememberthatthrowinganexceptionshouldbeaspecialeventandnotpartofnormalprogramexecution;thustheuseofstop()isdeprecatedinJava2.Theresalsoadestroy()method(whichhasneverbeenimplemented)thatyoushouldnevercallifyoucanavoiditsinceitsdrasticanddoesntreleaseobjectlocks.Blocked:Thethreadcouldberunbuttheressomethingthatpreventsit.WhileathreadisintheblockedstatetheschedulerwillsimplyskipoveritandnotgiveitanyCPUtime.Untilathreadreenterstherunnablestateitwontperformanyoperations.BecomingblockedTheblockedstateisthemostinterestingone,andisworthfurtherexamination.Athreadcanbecomeblockedforfivereasons:Youveputthethreadtosleepbycallingsleep(milliseconds),inwhichcaseitwillnotberunforthespecifiedtime.Youvesuspendedtheexecutionofthethreadwithsuspend().Itwillnotbecomerunnableagainuntilthethreadgetstheresume()message(thesearedeprecatedinJava2,andwillbeexaminedfurther).Youvesuspendedtheexecutionofthethreadwithwait().Itwillnotbecomerunnableagainuntilthethreadgetsthenotify()ornotifyAll()message.(Yes,thislooksjustlikenumber2,buttheresadistinctdifferencethatwillberevealed.)ThethreadiswaitingforsomeI/Otocomplete.Thethreadistryingtocallasynchronizedmethodonanotherobject,andthatobjectslockisnotavailable.Youcanalsocallyield()(amethodoftheThreadclass)tovoluntarilygiveuptheCPUsothatotherthreadscanrun.However,thesamethinghappensiftheschedulerdecidesthatyourthreadhashadenoughtimeandjumpstoanotherthread.Thatis,nothingpreventstheschedulerfrommovingyourthreadandgivingtimetosomeotherthread.Whenathreadisblocked,theressomereasonthatitcannotcontinuerunning.中文翻译(一)面向Java开发人员的Ajax:Ajax的Java对象序列化如果您正在使用异步JavaScript和XML(Ajax)进行JavaWeb开发,那么您最关心的问题可能就是把数据从服务器传递给客户机。在面向Java开发人员的Ajax系列的第二篇文章中,PhilipMcCarthy介绍了Java对象序列化的五种方式,并提供了选择最适合应用程序的数据格式和技术所需要的全部信息。下面介绍Ajax的构造块:(1)如何用JavaScriptXMLHttpRequest对象从Web页面向服务器发送异步请求。(2)如何用Javaservlet处理和响应请求(向客户机返回XML文档)。(3)如何在客户端用响应文档更新页面视图。这一次,我将讨论Ajax开发的基础知识,但是将侧重于许多JavaWeb开发人员最关心的问题:为客户机生成数据。多数Java开发人员已经把模型-视图-控制器(MVC)模式应用在他们的Web应用程序上。在传统的Web应用程序中,视图组件由JSP或者其他表示技术(例如Velocity模板)构成。这些表示组件动态地生成全新的HTML页面,替代用户以前正在查看的页面,从而更新用户界面。但是,在JavaWeb应用程序使用AjaxUI的情况下,基于从XMLHttpRequest的响应接收到的数据,JavaScript客户端代码对于更新用户看到的内容负有最终责任。从服务器的角度来看,视图成为它响应客户机请求而发送的数据表示。从Java类产生XML把Ajax响应作为XML来传递有许多原因:每个支持Ajax的浏览器都有导航XML文档的方法,也有许多服务器端技术可以处理XML数据。通过制定一个方案,描述要交换的文档类型,在Ajax客户端和服务器端之间很容易定义合约,而且如果服务器端架构采用面向服务的方式,那么使用XML也可以允许非Ajax客户机使用您提供的数据。自行进行序列化首先,可以从对象图以编程的方式生成XML。这种方式可以简单到只是在每个JavaBean类中实现toXml()方法即可。然后就可以选择合适的XMLAPI,让每个bean提供表示自己状态的元素,并递归地对自己的成员调用对象图。显然,这种方式无法扩展到大量的类,因为每个类都需要专门编写自己的XML生成代码。从好的方面来看,这是一个实现起来简单的方式,没有额外的配置支出或者更复杂的构建过程支出,任何JavaBean图都可以只用几个调用就变成XML文档。XML绑定框架近些年来,已经开发了多个JavaAPI来简化XML文档到Java对象图的绑定过程。多数都提供了XML编排和拆解;也就是说,它们可以在Java对象图和XML之间执行双向会话。这些框架封装了XML处理的全部工作,这意味着应用程序代码只需要处理普通的Java类。它们还希望提供有用的辅助功能,例如文档验证。笼统来说,这些框架采用了两种不同的方式:代码生成和对象到XML映射。我将分别解释这两种方式。代码生成方式使用代码生成的框架包括XMLBeans、JAXB、Zeus和JBind。Castor也能使用这项技术。这类框架的起点是描述文档数据类型的XML方案。使用框架提供的工具,就可以生成代表这些方案定义类型的Java类。最后,用这些生成的类编写应用程序,表示自己的模型数据,并通过框架提供的一些辅助机制把数据序列化成XML。如果应用程序要使用大型XML语法,那么代码生成方式是个很好的方法。在数十个类上编写定制XML序列化代码的可伸缩性问题由此消除。另一方面,也不再需要定义自己的JavaBean。框架生成的Java类通常非常符合XML的结构,所以对它们进行编码很难。而且,生成的类变成哑数据容器,因为一般不能向它们添加行为。一般来说,在应用程序代码中要做些妥协,才能很好地处理方案生成的类型。另一个缺陷是如果修改方案,会造成生成的类也要修改,所以也就会对围绕它们编写的代码带来相应的影响。这种类型的XML绑定框架在数据拆解时最有用(例如,使用XML文档并把它们转化成Java对象)。除非拥有大型数据模型而且有可能从生成的类中获益,否则基于代码生成的框架对于Ajax应用程序来说可能有很大的杀伤力。映射方式采用映射方式的框架包括Castor和ApacheCommonsBetwixt。映射通常是比代码生成更灵活和更轻量的解决方案。首先,可以像通常一样编写JavaBean,包括任何行为以及任何自己喜欢的方便的方法。然后,在运行时,调用框架中基于内省的编排器,并根据对象成员的类型、名称和值生成XML文档。通过定义类的映射文件,可以覆盖默认的绑定策略,并就类在XML中的表示方式对编排器提出建议。这种方法是在可伸缩性与灵活性之间的良好折中。可以按照自己喜欢的方式编写Java类,编排器负责处理XML。虽然映射定义文件编写起来简单,可伸缩性也足够好,但是映射规则最多只能改变标准的绑定行为,而且在对象结构和它们的XML表示之间总要残留一些耦合。最终,可能不得不在Java表示或XML格式之间任选一个做些折中,才能让映射方法起作用。数据绑定总结DennisSosnoski就XML数据绑定API的主题,在代码生成和代码映射两个方面写了深入的文章。如果想进一步研究这个领域,我推荐他在Castor和代码生成框架方面的精彩文章。总之,代码生成方式损失了过多的灵活性和方便性,对于典型的Ajax应用程序用处不大。另一方面,基于映射的框架可能工作得很好,但是要恰到好处地调整它们的映射策略,以便从对象生成需要的XML。所有的XML绑定API都具有手工序列化技术的一个主要不足:模型和视图的耦合。被限制为一个类型一个XML表示,就意味着在网络上总要有冗余数据传输。更严重的问题是,在情况要求客户端代码使用专门视图时,客户端代码却无法得到它,所以可能要费力地处理给定对象图的一成不变的视图。在传统的Web应用程序开发中,采用页面模板系统把视图生成与控制器逻辑和模型数据干净地分离。这种方法在Ajax场景中也会有帮助。(二)多线程利用对象,可将一个程序分割成相互独立的区域。我们通常也需要将一个程序转换成多个独立运行的子任务。像这样的每个子任务都叫作一个“线程”(Thread)。编写程序时,可将每个线程都想象成独立运行,而且都有自己的专用CPU。一些基础机制实际会为我们自动分割CPU的时间。我们通常不必关心这些细节问题,所以多线程的代码编写是相当简便的。这时理解一些定义对以后的学习狠有帮助。“进程”是指一种“自包容”的运行程序,有自己的地址空间。“多任务”操作系统能同时运行多个进程(程序)但实际是由于CPU分时机制的作用,使每个进程都能循环获得自己的CPU时间片。但由于轮换速度非常快,使得所有程序好象是在“同时”运行一样。“线程”是进程内部单一的一个顺序控制流。因此,一个进程可能容纳了多个同时执行的线程。多线程的应用范围很广。但在一般情况下,程序的一些部分同特定的事件或资源联系在一起,同时又不想为它而暂停程序其他部分的执行。这样一来,就可考虑创建一个线程,令其与那个事件或资源关联到一起,并让它独立于主程序运行。一个很好的例子便是“Quit”或“退出”按钮我们并不希望在程序的每一部分代码中都轮询这个按钮,同时又希望该按钮能及时地作出响应(使程序看起来似乎经常都在轮询它)。事实上,多线程最主要的一个用途就是构建一个“反应灵敏”的用户界面。从线程继承为创建一个线程,最简单的方法就是从Thread类继承。这个类包含了创建和运行线程所需的一切东西。Thread最重要的方法是run()。但为了使用run(),必须对其进行过载或者覆盖,使其能充分按自己的吩咐行事。因此,run()属于那些会与程序中的其他线程“并发”或“同时”执行的代码。下面这个例子可创建任意数量的线程,并通过为每个线程分配一个独一无二的编号(由一个静态变量产生),从而对不同的线程进行跟踪。Thread的run()方法在这里得到了覆盖,每通过一次循环,计数就减1计数为0时则完成循环(此时一旦返回run(),线程就中止运行)。/:SimpleThread.java/VerysimpleThreadingexamplepublicclassSimpleThreadextendsThreadprivateintcountDown=5;privateintthreadNumber;privatestaticintthreadCount=0;publicSimpleThread()threadNumber=+threadCount;System.out.println(Making+threadNumber);publicvoidrun()while(true)System.out.println(Thread+threadNumber+(+co
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论