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

上传人:muj****520 文档编号:156539464 上传时间:2022-09-27 格式:DOCX 页数:20 大小:36.22KB
收藏 版权申诉 举报 下载
Java程序设计教程 冶金工业出版社第9章pod_第1页
第1页 / 共20页
Java程序设计教程 冶金工业出版社第9章pod_第2页
第2页 / 共20页
Java程序设计教程 冶金工业出版社第9章pod_第3页
第3页 / 共20页
资源描述:

《Java程序设计教程 冶金工业出版社第9章pod》由会员分享,可在线阅读,更多相关《Java程序设计教程 冶金工业出版社第9章pod(20页珍藏版)》请在装配图网上搜索。

1、 第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); //休眠眠,等待待可能出出现的异异常情况况

2、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"" );; calPP

3、i(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 acccu

4、raacy)) 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 IntterrrupttedEExceeptiio

5、n((); iterratiion+++; signn = -siign;; thiss.laatesstPiiEsttimaate += (siign**4.00/(22*itteraatioon-11));; } } } //例程程9-22:SyynDeemo..javva /*演示示没有进进行线程程同步所所带来的的问题**/ publliccclasssSyynDeemo{{ publlic staaticc vooid maiin(SStriing[[] aargss){ Demoostrratoor ssharreDeemosstraatorr =

6、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(()

7、{ 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 ()++"

8、: coppy=""+coopy +"\\tshhareeDatta=""+shhareeDatta);; sharreDaata+++; } } } //例程程9-33:DeeadLLockkDemmo.jjavaa publlic claass DeaadLoockDDemoo{ publlic staaticc vooid maiin(SStriing[[] aargss){ DemooObjjectt a = nnew DemmoObbjecct()); DemooObjjectt b = nnew DemmoObbjecct())

9、; 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.meet

10、hood ((); } 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,,

11、no deaadloock happpenned""); } } } //例程程9-44:ThrreeTThreeadDDemoo.jaava /*ThhreeeThrreaddDemmo.jjavaa*/ publlic claass ThrreeTThreeadDDemoo{ puubliic sstattic voiid mmainn(Sttrinng[]] arrgs)){ //创建建新线程程 CCusttomTThreead ct11 = neww CuustoomThhreaad(00); CCusttomTThreead ct

12、22 = 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 CCus

13、ttomTThreead 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 (""CusstommT

14、hrreadd #""+ 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 cl

15、aass DiggitaalCllockk exxtennds JFrramee{ pubblicc sttatiic vvoidd maain((Strringg[] arggs) { JFFramme fframme == neew DDigiitallCloock((); frramee.shhow((); } pubblicc DiigittalCClocck()){ tthiss.seetSiize((2000,1550);; tthiss.seetDeefauul

16、tCClosseOpperaatioon(JJFraame..EXIIT_OON_CCLOSSE);; ///数字时时钟面板板 ffinaal CClocckPaane cp = nnew CloockPPanee();; //设置置按钮状状态并注注册事件件监听者者 ffinaal JJButttonn sttartt = neww JBButtton(("sttartt");; ffinaal JJButttonn sttop = nnew JBuuttoon(""stoop")); sstopp.s

17、eetEnnablled((fallse)); sstarrt.aaddAActiionLListteneer(nnew ActtionnLisstenner((){ puubliic vvoidd acctioonPeerfoormeed(AActiionEEvennt ee){ cpp.sttarttCloock((); sttartt.seetEnnablled((fallse)); sttop..settEnaableed(ttruee);

18、 } }}); sstopp.adddAcctioonLiisteenerr(neew AActiionLListteneer()){ pubblicc vooid acttionnPerrforrmedd(AcctioonEvventt e)){ cpp.sttopCClocck()); sttartt.seetEnnablled((truue);; sttop..settEnaableed(

19、ffalsse);; } }}); //设设置面板板布局 JJPannel butttommPanne == neew JJPannel((); bbutttomPPanee.addd(sstarrt);; bbutttomPPanee.addd(sstopp); JJPannel conntenntPaane = nnew JPaanell();; cconttenttPanne.ssetLLayoout((neww BoordeerLaayouut()))

20、; cconttenttPanne.aadd((cp,,BorrderrLayyoutt.CEENTEER);; cconttenttPanne.aadd((butttommPanne,BBordderLLayoout..SOUUTH)); tthiss.seetCoonteentPPanee(coonteentPPanee); tthiss.seetReesizzablle(ffalsse);; } } //例程程9-66:CloockPPanee.jaava /*数字字时钟面面板的实实现类**/ impoo

21、rt 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 { //线程程是否中中止的标标志 booo

22、leaan rrunnningg = fallse;; //用于于显示当当前时间间的字符符串 Strringg tiime = ""Cloock""; Fonnt ffontt = neww Foont(("SaanSeeriff", Fonnt.BBOLDD, 440);; //启动动报时器器 pubblicc vooid staartCClocck()) { thhis..runnninng == trrue;; Thhreaad tt = neww Thhreaad(tthiss);

23、 t..staart((); } //终止止报时器器 pubblicc vooid stoopCllockk() { thhis..runnninng == faalsee; } //实现现Runnnabble接接口的rrun()方方法 pubblicc vooid runn() { whhilee (tthiss.ruunniing)) { //获取取当前时时间并转转换成字字符串 tthiss.tiime = DDateeForrmatt.g

24、eetTiimeIInsttancce()).foormaat(nnew Datte())); tthiss.reepaiint((); //让当当前线程程休眠11秒钟 ttry { Thrreadd.slleepp(10000)); }} caatchh (IInteerruupteedExxcepptioon ee) {{ e.pprinntSttackkTraace(();

25、 }} } } //输出出当前时时间 pubblicc vooid paiintCCompponeent((Graaphiics g) { suuperr.paainttCommponnentt(g)); Grraphhicss2D g2 = ((Graaphiics22D) g; g22.seetFoont((thiis.ffontt); FoontRRendderCConttextt coonteex == g22.geetFoontRRe

26、ndderCConttextt();; Reectaanglle2DD booundd = thiis.ffontt.geetSttrinngBooundds(tthiss.tiime,, coonteex);; innt sstrXX = (innt) ((tthiss.geetWiidthh() - bbounnd.ggetWWidtth())) // 2)); innt sstrYY = (innt) ((tthiss.geetHeeighht()) - bouund..gettHeiightt())) /

27、 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 PPipeedOuutpuutSttrea

28、am ppoutt = neww PiipeddOuttputtStrreamm();; finaal PPipeedInnputtStrreamm piin == neew PPipeedInnputtStrreamm(poout)); //创建建并启动动输出线线程 Threead outtputtThrreadd = neww Thhreaad(nnew Runnnabble((){ publlic voiid rrun((){ writteByytess(poout)); } }); outpputTThreead..staart((); //创建建并启动动输

29、入线线程 Threead inpputTThreead = nnew Thrreadd(neew RRunnnablle()){ publlic voiid rrun((){ readdByttes((pinn); } }); inpuutThhreaad.sstarrt()); }cattch((IOEExceeptiion e){{ e.prrinttStaackTTracce()); } } //往管管道中写写入数据据 publlic staaticc vooid wriiteBBytees(OOutpputSStreeam outtstrream

30、m){ 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(

31、(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{{ DataaInpput

32、SStreeam 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"

33、"); 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..javva impoort javvax..swiing..*; impoort javva.aawt..*;

34、publlic claass Helllo__worrld exttendds JJAppplett{ publlic voiid ppainnt(GGrapphiccs gg){ g.drrawSStriing(("Heelloo,woorldd!",5,10)); } } HellloWoorldd.httml 代码 <>HELLLO,,WORRLD!!<> > > >

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

相关资源

更多
正为您匹配相似的精品文档
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  sobing.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!