仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 461|回复: 10
打印 上一主题 下一主题

[学习教程] JAVA网站制作之Threads

[复制链接]
因胸联盟 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:23:06 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-11-15 05:13

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表