仓酷云
标题:
JAVA网站制作之Threads
[打印本页]
作者:
因胸联盟
时间:
2015-1-18 11:23
标题:
JAVA网站制作之Threads
一旦你有了思想,那你编的程序就有了灵魂,不管是什么语言到了你的手里都会是你的工具而已,他们的价值是能尽快帮助你实现你想要的目标。但是如果你没有了思想,那就像是海里的帆船失去了船帆,是很难到打海的另一边的。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比较难
作者:
飘飘悠悠
时间:
2015-1-20 23:08
是一种使网页(Web Page)由静态(Static)转变为动态(Dynamic)的语言
作者:
若相依
时间:
2015-1-26 17:28
学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。
作者:
灵魂腐蚀
时间:
2015-1-31 05:13
J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。
作者:
admin
时间:
2015-2-6 17:25
是一种使网页(Web Page)产生生动活泼画面的语言
作者:
仓酷云
时间:
2015-2-17 09:18
是一种使用者不需花费很多时间学习的语言
作者:
简单生活
时间:
2015-2-26 03:29
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
作者:
小魔女
时间:
2015-3-8 11:40
在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。
作者:
爱飞
时间:
2015-3-10 20:39
科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。
作者:
小女巫
时间:
2015-3-17 09:55
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
作者:
精灵巫婆
时间:
2015-3-24 06:10
还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。
欢迎光临 仓酷云 (http://ckuyun.com/)
Powered by Discuz! X3.2