马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
一旦你有了思想,那你编的程序就有了灵魂,不管是什么语言到了你的手里都会是你的工具而已,他们的价值是能尽快帮助你实现你想要的目标。但是如果你没有了思想,那就像是海里的帆船失去了船帆,是很难到打海的另一边的。7)Threads
Objective1)
Writecodetodefine,instantiateandstartnewthreadsusingbothjava.lang.Threadandjava.lang.Runnable
・Javaisfundamentallymulti-threaded.
・Everythreadcorrespondstoaninstanceofjava.lang.Threadclassorasub-class.
・Athreadbecomeseligibletorun,whenitsstart()methodiscalled.Threadschedulerco-ordinatesbetweenthethreadsandallowsthemtorun.
・Whenathreadbeginsexecution,theschedulercallsitsrunmethod.
SignatureofrunmethodCpublicvoidrun()
・Whenathreadreturnsfromitsrunmethod(orstopmethodiscalledCdeprecatedin1.2),itsdead.Itcannotberestarted,butitsmethodscanbecalled.(it’sjustanobjectnomoreinarunningstate)
・Ifstartiscalledagainonadeadthread,IllegalThreadStateExceptionisthrown.
・Whenathreadisinrunningstate,itmaymoveoutofthatstateforvariousreasons.Whenitbecomeseligibleforexecutionagain,threadschedulerallowsittorun.
・Therearetwowaystoimplementthreads.
1.ExtendThreadclass
publicclassThreadextendsObjectimplementsRunnable
Thread()
Thread(Runnabletarget)
Thread(Runnabletarge,Stringname)
Thread(Stringname)
Thread(ThreadGroupgroup,Runnabletarget)
Thread(ThreadGroupgroup,Runnabletarget,Stringname)
Thread(ThreadGroupgroup,Stringname)
・Createanewclass,extendingtheThreadclass.
・Provideapublicvoidrunmethod,otherwiseemptyruninThreadclasswillbeexecuted.
・Createaninstanceofthenewclass.
・Callstartmethodontheinstance(don’tcallrunCitwillbeexecutedonthesamethread)
2.ImplementRunnableinterface
publicinterfaceRunnable
onlyonemethod:publicvoidrun
・CreateanewclassimplementingtheRunnableinterface.
・Provideapublicvoidrunmethod.
・Createaninstanceofthisclass.
・CreateaThread,passingtheinstanceasatargetCnewThread(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.2
2.Time-slicedorRoundRobinScheduling
・Athreadisonlyallowedtoexecuteforacertainamountoftime.Afterthat,ithastocontendfortheCPU(virtualCPU,JVM)timewithotherthreads.
・Thispreventsahigh-prioritythreadmono-policingtheCPU.
・ThedrawbackwiththisschedulingisCitcreatesanon-deterministicsystemCatanypointintime,youcannottellwhichthreadisrunningandhowlongitmaycontinuetorun.
・MactinoshJVM’s
・WindowsJVM’safterJava1.0.2
OfthetwomethodsofcreatinganewthreadtheuseofRunnableisprobablymorecommon.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)
・TwooverloadedversionsConewithmilliseconds,onewithmillisecondsandnanoseconds.
・ThrowsanInterruptedException.(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.
5.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.println("loopingwhile");
}
}catch(InterruptedExceptionie){}
}
}
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,toobtainverybrieflockingCnotverycommon
・Iftargetisnull,thentheNullPointerExceptionisthrown.
・waitCpointstoremember
§callingthreadgivesupCPU
§callingthreadgivesupthelock
§callingthreadgoestomonitor’swaitingpool
§waitalsohasaversionwithtimeoutinmilliseconds.Usethisifyou’renotsurewhenthecurrentthreadwillgetnotified,thisavoidsthethreadbeingstuckinwaitstateforever.
・notifyCpointstoremember
§onethreadgetsmovedoutofmonitor’swaitingpooltoreadystate
§notifyAllmovesallthethreadstoreadystate
§Threadgetstoexecutemustre-acquirethelockofthemonitorbeforeitcanproceed.
・Notethedifferencesbetweenblockedandwaiting.
BlockedWaiting
Threadiswaitingtogetalockonthemonitor.(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’,thethreadkeepsthelocksitobtainedCsosuspendisdeprecatedin1.2
・Useofstopisalsodeprecated,insteaduseaflaginrunmethod.Compilerwon’twarnyou,ifyouhavestatementsafteracalltostop,eventhoughtheyarenotreachable.
Atypicalexampleofusingthewait/notifyprotocoltoallowcommunicationbetweenThreadsappearstoinvolveapparentlyendlessloopssuchas
//producingcode
while(true){
try{
wait();
}catch(InterruptedExceptione){}
}
//someproducingactiongoeshere
notifyAll();
Conditionsthatmightpreventathreadfromexecuting:
xThethreadisnotthehighestprioritythreadandsocannotgetCPUtime.
xThethreadiswaitingonaconditionbecausesomeoneinvokedwait()forthethread.
xThethreadhasexplicitlyyieldedcontrolbyinvokingyield()toallowanotherthreadofthesameprioritytorun.
xThethreadhasbeenputtosleepusingthesleep()method
xSomeonehassuspendedthethreadusingthesuspend()method.(deprecatedinJava2)
xItisblockedforfileI/O
xThereismorethanonethreadwiththesamehighestpriorityandJVMisswitchingbetweenthesethreads,atthemoment,thethreadinquestionisawaitingCPUtime.
你精通任何一门语言就最强大。现在来看,java的市场比C#大,C#容易入手,比较简单,java比较难 |