当前位置首页 > 行业资料 > 冶金工业
搜柄,搜必应! 快速导航 | 使用教程

Java程序设计教程 冶金工业出版社第9章pod

文档格式:DOCX| 20 页|大小 36.22KB|2022-09-27 发布|举报 | 版权申诉
第1页
第2页
第3页
下载文档到电脑,查找使用更方便 还剩页未读,继续阅读>>
1 / 20
此文档下载收益归作者所有 下载文档
  • 版权提示
  • 文本预览
  • 常见问题
  • 第9章多多线程与与Appplett//例程程9-11:Pii.jaava/*演示示采用多多线程技技术计算算圆周率率*/publlic claass Pi{{publlic staaticc vooid maiin(SStriing[[] aargss){PiCaacullatoor pc = nnew PiCCacuulattor(();Threead t == neew TThreead((pc));t.sttartt();;try{{Threead..sleeep (1000000); //休眠眠,等待待可能出出现的异异常情况况t.innterrruppt ();;}cattch((IntterrrupttedEExceeptiion e){{e.prrinttStaackTTracce());}}}classs PPiCaacullatoor iimpllemeentss Ruunnaablee{privvatee douublee laatesstPiiEsttimaate;;publlic voiid rrun((){try{{Systtem..outt.prrintt (""Matth.PPI == "++ Matth.PPI + ""\t"" );;calPPi(00.0000011);Systtem..outt.prrinttln ("tthe lattestt PI = ""+thhis..lattesttPiEEstiimatte ));}cattch((IntterrrupttedEExceeptiion e){{Systtem..outt.prrinttln(("Thhe cacculaatorr iss Innterrrupptedd."));}} /***用于计计算圆周周率的方方法,aaccuuraccy为计计算精度度*/privvatee voiid ccalPPi(ddoubble acccuraacy)) thhrowws IInteerruupteedExxcepptioon {thiss.laatesstPiiEsttimaate =0..0;longg itteraatioon = 00;int siggn == -11;//按给给定精度度计算圆圆周率whille(MMathh.abbs ((Matth.PPI-tthiss.laatesstPiiEsttimaate))>acccurracyy){if(TThreead..intterrruptted ()))throow nnew IntterrrupttedEExceeptiion(();iterratiion+++;signn = -siign;;thiss.laatesstPiiEsttimaate += (siign**4.00/(22*itteraatioon-11));;}}}//例程程9-22:SyynDeemo..javva/*演示示没有进进行线程程同步所所带来的的问题**/publliccclasssSyynDeemo{{publlic staaticc vooid maiin(SStriing[[] aargss){Demoostrratoor ssharreDeemosstraatorr = neww Deemosstraatorr();;Threead t1 = nnew Thrreadd(shhareeDemmosttrattor,,"t11");;Threead t2 = nnew Thrreadd(shhareeDemmosttrattor,,"t22");;t1.sstarrt());t2.sstarrt());}}classs DDemoostrratoor iimpllemeentss Ruunnaablee{privvatee innt ssharreDaata = 00;publlic voiid rrun((){Threead t == Thhreaad.ccurrrenttThrreadd ());for((intt i = 11; ii <== 5;; i+++){{int coppy == shhareeDatta;try{{Threead..sleeep ((iint))(Maath..ranndomm ())*10000)));}cattch((Exccepttionn e)){e.prrinttStaackTTracce());}Systtem..outt.prrinttln ("TThreead "+tt.geetNaame ()++": coppy=""+coopy +"\\tshhareeDatta=""+shhareeDatta);;sharreDaata+++;}}}//例程程9-33:DeeadLLockkDemmo.jjavaapubllic claass DeaadLoockDDemoo{publlic staaticc vooid maiin(SStriing[[] aargss){DemooObjjectt a = nnew DemmoObbjecct());DemooObjjectt b = nnew DemmoObbjecct());a.annothher = bb;b.annothher = aa;Threead t1 = nnew Thrreadd(a,,"t11");;Threead t2 = nnew Thrreadd(b,,"t22");;t1.sstarrt (();t2.sstarrt (();}}classs DDemooObjjectt immpleemennts Runnnabble{{publlic DemmoObbjecct aanottherr = nulll;publlic voiid rrun((){thiss.meethood (();}publlic synnchrroniizedd vooid metthodd(){{if(tthiss.annothher != nulll){{try{{Threead..sleeep (10000));}cattch((Exccepttionn e)){e.prrinttStaackTTracce());}anottherr.meethood (();//下面面的代码码段实际际上是执执行不到到的Systtem..outt.prrinttln ("IIf yyou cann seee tthiss liine,,no deaadloock happpenned"");}}}//例程程9-44:ThrreeTThreeadDDemoo.jaava/*ThhreeeThrreaddDemmo.jjavaa*/publlic claass ThrreeTThreeadDDemoo{ puubliic sstattic voiid mmainn(Sttrinng[]] arrgs)){//创建建新线程程 CCusttomTThreead ct11 = neww CuustoomThhreaad(00); CCusttomTThreead ct22 = neww CuustoomThhreaad(11); ///启动新新线程 cct1..staart ();; cct2..staart ();;//输出出maiin线程程信息 ffor((intt i = 00; ii < 5; i+++){ Sysstemm.ouut.pprinntlnn("mmainn thhreaad: "+ii); }} SSysttem..outt.prrinttln ("mmainn thhreaad hhas donne!""); }}classs CCusttomTThreead exttendds TThreead{{ innt iid; puubliic CCusttomTThreead((intt cuustoomThhreaadIDD){ tthiss.idd = cusstommThrreaddID;; }//重定定义子线线程的rrun(()方法 puubliic vvoidd ruun()){//输出出自定义义线程的的信息 ffor((intt i = 00; ii < 5; i+++){ Sysstemm.ouut.pprinntlnn (""CusstommThrreadd #""+ tthiss.idd +"": ""+i)); }} SSysttem..outt.prrinttln ("CCusttomTThreead #"++thiis.iid+"" haas ddonee!")); }}//例程程9-55:DiggitaalCllockk.jaava/*采用用多线程程技术演演示一个个简单的的数字时时钟*//impoort javva.aawt..eveent..*;impoort javva.aawt..*;impoort javvax..swiing..*;publlic claass DiggitaalCllockk exxtennds JFrramee{ pubblicc sttatiic vvoidd maain((Strringg[] arggs) { JFFramme fframme == neew DDigiitallCloock((); frramee.shhow((); } pubblicc DiigittalCClocck()){ tthiss.seetSiize((2000,1550);; tthiss.seetDeefauultCClosseOpperaatioon(JJFraame..EXIIT_OON_CCLOSSE);; ///数字时时钟面板板 ffinaal CClocckPaane cp = nnew CloockPPanee();;//设置置按钮状状态并注注册事件件监听者者 ffinaal JJButttonn sttartt = neww JBButtton(("sttartt");; ffinaal JJButttonn sttop = nnew JBuuttoon(""stoop")); sstopp.seetEnnablled((fallse)); sstarrt.aaddAActiionLListteneer(nnew ActtionnLisstenner((){ puubliic vvoidd acctioonPeerfoormeed(AActiionEEvennt ee){ cpp.sttarttCloock((); sttartt.seetEnnablled((fallse)); sttop..settEnaableed(ttruee); } }}); sstopp.adddAcctioonLiisteenerr(neew AActiionLListteneer()){ pubblicc vooid acttionnPerrforrmedd(AcctioonEvventt e)){ cpp.sttopCClocck()); sttartt.seetEnnablled((truue);; sttop..settEnaableed(ffalsse);; } }}); //设设置面板板布局 JJPannel butttommPanne == neew JJPannel((); bbutttomPPanee.addd(sstarrt);; bbutttomPPanee.addd(sstopp); JJPannel conntenntPaane = nnew JPaanell();; cconttenttPanne.ssetLLayoout((neww BoordeerLaayouut())); cconttenttPanne.aadd((cp,,BorrderrLayyoutt.CEENTEER);; cconttenttPanne.aadd((butttommPanne,BBordderLLayoout..SOUUTH)); tthiss.seetCoonteentPPanee(coonteentPPanee); tthiss.seetReesizzablle(ffalsse);; }}//例程程9-66:CloockPPanee.jaava/*数字字时钟面面板的实实现类**/impoort javvax..swiing..JPaanell;impoort javva.uutill.*;;impoort javva.aawt..*;impoort javva.aawt..fonnt.FFonttRennderrConntexxt;impoort javva.aawt..geoom.**;impoort javva.ttextt.*;;publlic claass CloockPPanee exxtennds JPaanell immpleemennts Runnnabble {//线程程是否中中止的标标志 boooleaan rrunnningg = fallse;;//用于于显示当当前时间间的字符符串 Strringg tiime = ""Cloock""; Fonnt ffontt = neww Foont(("SaanSeeriff", Fonnt.BBOLDD, 440);;//启动动报时器器 pubblicc vooid staartCClocck()) { thhis..runnninng == trrue;; Thhreaad tt = neww Thhreaad(tthiss); t..staart((); }//终止止报时器器 pubblicc vooid stoopCllockk() { thhis..runnninng == faalsee; }//实现现Runnnabble接接口的rrun()方方法 pubblicc vooid runn() { whhilee (tthiss.ruunniing)) {//获取取当前时时间并转转换成字字符串 tthiss.tiime = DDateeForrmatt.geetTiimeIInsttancce()).foormaat(nnew Datte())); tthiss.reepaiint(();//让当当前线程程休眠11秒钟 ttry { Thrreadd.slleepp(10000)); }} caatchh (IInteerruupteedExxcepptioon ee) {{ e.pprinntSttackkTraace((); }} } }//输出出当前时时间 pubblicc vooid paiintCCompponeent((Graaphiics g) { suuperr.paainttCommponnentt(g)); Grraphhicss2D g2 = ((Graaphiics22D) g; g22.seetFoont((thiis.ffontt); FoontRRendderCConttextt coonteex == g22.geetFoontRRendderCConttextt();; Reectaanglle2DD booundd = thiis.ffontt.geetSttrinngBooundds(tthiss.tiime,, coonteex);; innt sstrXX = (innt) ((tthiss.geetWiidthh() - bbounnd.ggetWWidtth())) // 2)); innt sstrYY = (innt) ((tthiss.geetHeeighht()) - bouund..gettHeiightt())) / 2) + 440; g22.drrawSStriing((thiis.ttimee, sstrXX, sstrYY); }}//例程程9-77:IOOPippeDeemo..javva/*演示示采用管管道机制制的线程程间通信信*/impoort javva.iio.**;publlic claass IOPPipeeDemmo{publlic staaticc vooid maiin(SStriing[[] aargss){try{{//创建建并连接接管道finaal PPipeedOuutpuutSttreaam ppoutt = neww PiipeddOuttputtStrreamm();;finaal PPipeedInnputtStrreamm piin == neew PPipeedInnputtStrreamm(poout));//创建建并启动动输出线线程Threead outtputtThrreadd = neww Thhreaad(nnew Runnnabble((){publlic voiid rrun((){writteByytess(poout));}});outpputTThreead..staart(();//创建建并启动动输入线线程Threead inpputTThreead = nnew Thrreadd(neew RRunnnablle()){publlic voiid rrun((){readdByttes((pinn);}});inpuutThhreaad.sstarrt());}cattch((IOEExceeptiion e){{e.prrinttStaackTTracce());}}//往管管道中写写入数据据publlic staaticc vooid wriiteBBytees(OOutpputSStreeam outtstrreamm){try{{DataaOuttputtStrreamm ouut == neew DDataaOuttputtStrreamm(new BuffferredOOutpputSStreeam((outtstrreamm) );Threead t == Thhreaad.ccurrrenttThrreadd ());for((intt i==0; i<110; i+++){Systtem..outt.prrinttln ("wwritte iinteegerr "++i+"" too piipe..");;out..wriiteIInt((i);;t.yiieldd ());}out..fluush(();out..cloose(();Systtem..outt.prrinttln ("WWritte ddataa too piipe hass doone"");}cattch((IOEExceeptiion e){{e.prrinttStaackTTracce());}}//从管管道中读读取数据据publlic staaticc vooid reaadByytess(InnputtStrreamm innputtstrreamm){try{{DataaInpputSStreeam in = nnew DattaInnputtStrreamm(new BuffferredIInpuutSttreaam(iinpuutsttreaam) );Threead t == Thhreaad.ccurrrenttThrreadd ());boolleann eoof == faalsee;whille(!!eoff){try{{int i == inn.reeadIInt(();Systtem..outt.prrinttln(("Reead inttegeer ""+i++" ffromm piipe"");t.yiieldd ());}cattch((EOFFExccepttionn e)){eof = ttruee;}}Systtem..outt.prrinttln ("RReadd daata froom ppipee haas ddonee");;}cattch((IOEExceeptiion e){{e.prrinttStaackTTracce());}}}//例程程9-8 Heelloo_Worrld..javvaimpoort javvax..swiing..*;impoort javva.aawt..*;publlic claass Helllo__worrld exttendds JJAppplett{publlic voiid ppainnt(GGrapphiccs gg){g.drrawSStriing(("Heelloo,woorldd!",5,10));}}HellloWoorldd.httml 代码<>HELLLO,,WORRLD!!<>>>>。

    点击阅读更多内容
    卖家[上传人]:mujiubi520
    资质:实名认证
    相关文档
    正为您匹配相似的精品文档