java多线程机制

java多线程机制

ID:27533878

大小:86.00 KB

页数:8页

时间:2018-12-03

上传者:U-991
java多线程机制_第1页
java多线程机制_第2页
java多线程机制_第3页
java多线程机制_第4页
java多线程机制_第5页
资源描述:

《java多线程机制》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库

ThreadsObjective1)Writecodetodefine,instantiateandstartnewthreadsusingbothjava.Iang.Threadandjava.lang.Runnable•Javaisfundamentallymulti-threaded.•Everythreadcorrespondstoaninstanceofjava.Iang.Threadclassorasub-class.•Athreadbecomeseligibletorun,whenitsstart()methodiscalled.Threadschedulerco-ordinatesbetweenthethreadsandallowsthemtorun.•Whenathreadbeginsexecution,theschedulercallsitsrunmethod.Signatureofrunmethod-publicvoidrun()•Whenathreadreturnsfromitsrunmethod(orstopmethodiscalled-deprecatedin1.2),itsdead.Itcannotberestarted,butitsmethodscanbecalled,(it’sjustanobjectnomoreinarunningstate)•Ifstartiscalledagainonadeadthread,IllegalThreadStateExceptionisthrown.•Whenathreadisinrunningstate,itmaymoveoutofthatstateforvariousreasons.Whenitbecomeseligibleforexecutionagain,threadschedulerallowsittorun.•Therearetwowaystoimplementthreads.1.ExtendThreadclasspublicclassThreadextendsObjectimplementsRunnableThread()Thread(Runnabletarget)Thread(Runnabletarge,Stringname)Thread(Stringname)Thread(ThreadGroupgroup,Runnabletarget)Thread(ThreadGroupgroup,Runnabletarget,Stringname)Thread(ThreadGroupgroup,Stringname)•Createanewclass,extendingtheThreadclass.•Provideapublicvoidrunmethod,otherwiseemptyruninThreadclasswillbeexecuted.•Createaninstanceofthenewclass.•Callstartmethodontheinstance(don’tcallrun-itwillbeexecutedonthesamethread)2.ImplementRunnableinterfacepublicinterfaceRunnableonlyonemethod:publicvoidrun•CreateanewclassimplementingtheRunnableinterface.•Provideapublicvoidrunmethod. •Createaninstanceofthisclass. •CreateaThread,passingtheinstanceasatarget-newThread(object)•TargetshouldimplementRunnable,Threadclassimplementsit,soitcanbeatargetitself.•CallthestartmethodontheThread.•JVMcreatesoneuserthreadforrunningaprogram.Thisthreadiscalledmainthread.Themainmethodoftheclassiscalledfromthemainthread.Itdieswhenthemainmethodends.Ifotheruserthreadshavebeenspawnedfromthemainthread,programkeepsrunningevenifmainthreaddies.Basicallyaprogramrunsuntilalltheuserthreads(non-daemonthreads)aredead.•AthreadcanbedesignatedasadaemonthreadbycallingsetDaemon(boolean)method.Thismethodshouldbecalledbeforethethreadisstarted,otherwiseIllegalThreadStateExceptionwillbethrown.•Athreadspawnedbyadaemonthreadisadaemonthread.•Threadshavepriorities.ThreadclasshaveconstantsMAX_PRIORITY(10),MIN_PRIORITY(1),NORM_PRIORITY(5)•Anewlycreatedthreadgetsitspriorityfromthecreatingthread.Normallyit’llbeNORM_PRIORITY.•getPriorityandsetPriorityarethemethodstodealwithpriorityofthreads.•JavaleavestheimplementationofthreadschedulingtoJVMdevelopers.Twotypesofschedulingcanbedone.1.Pre-emptiveScheduling.Waysforathreadtoleaverunningstate-•Itcanceasetobereadytoexecute(bycallingablockingi/omethod)•Itcangetpre-emptedbyahigh-prioritythread,whichbecomesreadytoexecute.•Itcanexplicitlycallathread-schedulingmethodsuchaswaitorsuspend.•SolarisJVM’sarepre-emptive.•WindowsJVM’swerepre-emptiveuntilJava1.0.22.Time-slicedorRoundRobinScheduling•Athreadisonlyallowedtoexecuteforacertainamountoftime.Afterthat,ithastocontendfortheCPU(virtualCPU,JVM)timewithotherthreads.•Thispreventsahigh-prioritythreadmono-policingtheCPU.•Thedrawbackwiththisschedulingis-itcreatesanon-deterministicsystem-atanypointintime,youcannottellwhichthreadisrunningandhowlongitmaycontinuetorun.•MactinoshJVM’s•WindowsJVM’safterJava1.0.2OfthetwomethodsofcreatinganewthreadtheuseofRunnableisprobablymorecommon.TheothermethodforcreatingathreadistocreateaclassthatisdescendedfromThread.Thisiseasytodobutitmeansyoucannotinheritfromanyotherclass, Objective2)Recognizeconditionsthatmightpreventathreadfromexecuting.Differentstatesofathread:1.Yielding•Yieldisapublicstaticvoidmethod.Operatesoncurrentthread.Forstaticmethod,callThread.yield()isok,don’tneedcallt.yield(),wheretisinstanceofThread,butcompilerwillpassit.•Movesthethreadfromrunningtoreadystate.•Iftherearenothreadsinreadystate,theyieldedthreadmaycontinueexecution,otherwiseitmayhavetocompetewiththeotherthreadstorun.•Runthethreadsthataredoingtime-consumingoperationswithalowpriorityandcallyieldperiodicallyfromthosethreadstoavoidthosethreadslockinguptheCPU.2.Sleeping•Sleepisalsoapublicstaticvoidmethod.•Sleepsforacertainamountoftime,(passingtimewithoutdoinganythingandw/ousingCPU)•Twooverloadedversions-onewithmilliseconds,onewithmillisecondsandnanoseconds.•ThrowsanInteiTuptedException.(mustbecaught)•Afterthetimeexpires,thesleepingthreadgoestoreadystate.Itmaynotexecuteimmediatelyafterthetimeexpires.Ifthereareotherthreadsinreadystate,itmayhavetocompetewiththosethreadstorun.Thecorrectstatementisthesleepingthreadwouldexecutesometimeafterthespecifiedtimeperiodhaselapsed.•Ifinterruptmethodisinvokedonasleepingthread,thethreadmovestoreadystate.Thenexttimeitbeginsrunning,itexecutestheInterruptedExceptionhandler.3.Suspending•Suspendandresumeareinstancemethodsandaredeprecatedin1.2•Athreadthatreceivesasuspendcall,goestosuspendedstateandstaysthereuntilitreceivesaresumecallonit-•Athreadcansuspendititself,oranotherthreadcansuspendit.•But,athreadcanberesumedonlybyanotherthread.•Callingresumeonathreadthatisnotsuspendedhasnoeffect.•Compilerwon’twarnyouifsuspendandresumearesuccessivestatements,althoughthethreadmaynotbeabletoberestarted.4.Blocking•MethodsthatareperformingI/Ohavetowaitforsomeoccurrenceintheoutsideworldtohappenbeforetheycanproceed.Thisbehaviorisblocking.•IfamethodneedstowaitanindeterminableamountoftimeuntilsomeI/Otakesplace,thenthethreadshouldgraciouslystepoutoftheCPU.AllJavaI/Omethodsbehavethisway.•Athreadcanalsobecomeblocked,ifitfailedtoacquirethelockofamonitor. 1.Waiting•wait,notifyandnotifyAllmethodsarenotcalledonThread,they’recalledonObject.Becausetheobjectistheonewhichcontrolsthethreadsinthiscase.Itasksthethreadstowaitandthennotifieswhenitsstatechanges.It’scalledamonitor.•Waitputsanexecutingthreadintowaitingstate.(tothemonitor’swaitingpool)•Notifymovesonethreadinthemonitor’swaitingpooltoreadystate.Wecannotcontrolwhichthreadisbeingnotified.notifyAllisrecommended.•NotifyAllmovesallthreadsinthemonitor’swaitingpooltoready.•Thesemethodscanonlybecalledfromsynchronizedcode,oranIllegalMonitorStateExceptionwillbethrown.Inotherwords,onlythethreadsthatobtainedtheobject’slockcancallthesemethods.Thesleepmethodisstaticandpausesexecutionforasetnumberofmilliseconds.Thereisaversionthatissupposedtopauseforasetnumberofnanoseconds,HereisanexampleofputtingaThreadtosleep,notehowthesleepmethodthrowsInterruptedException.publicclassTSleepextendsThread{publicstaticvoidmain(Stringargv[]){TSleept=newTSleep();t•start();}publicvoidrun(){try{while(true){this.sleep(1000);System•out•printIn(’’loopingwhile’’);}}catch(工nterruptedExceptionie){}}}Objective3)WritecodeusingsynchronizedwaitnotifyandnotifyAlltoprotectagainstconcurrentaccessproblemsandtocommunicatebetweenthreads.DefinetheinteractionbetweenthreadsandbetweenthreadsandobjectlockswhenexecutingsynchronizedwaitnotifyornotifyAll.Locks,MonitorsandSynchronization•Everyobjecthasalock(foreverysynchronizedcodeblock).Atanymoment,thislockiscontrolledbyatmostonethread.•Athreadthatwantstoexecuteanobject’ssynchronizedcodemustacquirethelockoftheobject.Ifitcannotacquirethelock,thethreadgoesintoblockedstateandcomestoreadyonlywhentheobject’slockisavailable. •Whenathread,whichownsalock,finishesexecutingthesynchronizedcode,itgivesupthelock.•Monitorisanobjectthatcanblockandrevivethreads,anobjectthatcontrolsclientthreads.Askstheclientthreadstowaitandnotifiesthemwhenthetimeisrighttocontinue,basedonitsstate.InstrictJavaterminology,anyobjectthathassomesynchronizedcodeisamonitor.•2waystosynchronize:1.Synchronizetheentiremethod•Declarethemethodtobesynchronized-verycommonpractice.•Threadshouldobtaintheobject’slock.2.Synchronizepartofthemethod•Havetopassanarbitraryobjectwhichlockistobeobtainedtoexecutethesynchronizedcodeblock(partofamethod).Synchronized(target){statements}•Wecanspecify“this”inplaceobject,toobtainverybrieflocking—notverycommon•Iftargetisnull,thentheNullPointerExceptionisthrown.•wait-pointstoremember■callingthreadgivesupCPU■callingthreadgivesupthelock■callingthreadgoestomonitor’swaitingpool■waitalsohasaversionwithtimeoutinmilliseconds.Usethisifyou’renotsurewhenthecurrentthreadwillgetnotified,thisavoidsthethreadbeingstuckinwaitstateforever.•notify-pointstoremember■onethreadgetsmovedoutofmonitor'swaitingpooltoreadystate■notifyAllmovesallthethreadstoreadystate■Threadgetstoexecutemustre-acquirethelockofthemonitorbeforeitcanproceed.•Notethedifferencesbetweenblockedandwaiting.BlockedWaitingThreadiswaitingtogetalockonthemonitor.(orwaitingforablockingi/omethod)Threadhasbeenaskedtowait,(bymeansofwaitmethod)Causedbythethreadtriedtoexecutesomesynchronizedcode,(orablockingi/omethod)Thethreadalreadyacquiredthelockandexecutedsomesynchronizedcodebeforecomingacrossawaitcall.Canmovetoreadyonlywhenthelockisavailable.(orthei/ooperationiscomplete)Canmovetoreadyonlywhenitgetsnotified(bymeansofnotifyornotifyAll)•Pointsforcomplexmodels:1.Alwayscheckmonitor’sstateinawhileloop,ratherthaninanifstatement.2.AlwayscallnotifyAll,insteadofnotify. •waitandsleepmustbeenclosedinatry/catchforInterruptedException.•Asinglethreadcanobtainmultiplelocksonmultipleobjects(oronthesameobject)•Athreadowningthelockofanobjectcancallothersynchronousmethodsonthesameobject(thisisanotherlock)Otherthreadscan’tdothat.Theyshouldwaittogetthelock.•Non-synchronousmethodscanbecalledatanytimebyanythread.•Synchronousmethodsarere-entrant.Sotheycanbecalledrecursively.•Synchronizedmethodscanbeoverridedtobenon-synchronous.synchronizedbehavioraffectsonlytheoriginalclass.•Locksoninner/outerobjectsareindependent.Gettingalockonouterobjectdoesn’tmeangettingthelockonaninnerobjectaswell,thatlockshouldbeobtainedseparately.•LocksonstaticsynchronizedmethodcalledClasswidelock.Theclasswidelockandtheinstancelockbeingindependentofeachother.•waitandnotifyshouldbecalledfromsynchronizedcode.Thisensuresthatwhilecallingthesemethodsthethreadalwayshasthelockontheobject.Ifyouhavewait/notifyinnon-synchronizedcodecompilerwon’tcatchthis.Atruntime,ifthethreaddoesn’thavethelockwhilecallingthesemethods,anIllegalMonitorStateExceptionisthrown.•Deadlockscanoccureasily,e.g,ThreadAlockedObjectAandwaitingtogetalockonObjectB,butThreadBlockedObjectBandwaitingtogetalockonObjectA.They’llbeinthisstateforever.•It’stheprogrammer’sresponsibilitytoavoidthedeadlock.Alwaysgetthelocksinthesameorder.•While‘suspended’,thethreadkeepsthelocksitobtained-sosuspendisdeprecatedin1.2•Useofstopisalsodeprecated,insteaduseaflaginrunmethod.Compilerwon’twarnyou,ifyouhavestatementsafteracalltostop,eventhoughtheyarenotreachable.Atypicalexampleofusingthewait/notifyprotocoltoallowcommunicationbetweenThreadsappearstoinvolveapparentlyendlessloopssuchas//producingcodewhile(true){try{wait();}catch(InterruptedExceptione){}}//someproducingactiongoesherenotifyAll();Conditionsthatmightpreventathreadfromexecuting:♦ThethreadisnotthehighestprioritythreadandsocannotgetCPUtime.♦Thethreadiswaitingonaconditionbecausesomeoneinvokedwait()forthethread. ♦ThethreadhasexplicitlyyieldedcontrolbyinvokingyieldOtoallowanotherthreadofthesameprioritytorun.♦Thethreadhasbeenputtosleepusingthesleep()method♦SomeonehassuspendedthethreadusingthesuspendOmethod,(deprecatedinJava2)♦ItisblockedforfileI/O♦ThereismorethanonethreadwiththesamehighestpriorityandJVMisswitchingbetweenthesethreads,atthemoment,thethreadinquestionisawaitingCPUtime.

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
关闭