欢迎来到天天文库
浏览记录
ID:40241403
大小:158.01 KB
页数:40页
时间:2019-07-28
《《lecture7.javathreads》》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Lecture7.JavaThreadsCheng-ChiaChenContentsWhatisathread?DefineandlaunchathreadThelife-cycleofathreadinterruptathreadthreadsynchronizationotherissuesWhatisathread?Asequential(orsingle-threaded)programisonethat,whenexecuted,hasonlyonesingleflowofcontrol.i.e.,atanytimeinstant,thereisat
2、mostonlyoneinstruction(orstatementorexecutionpoint)thatisbeingexecutedintheprogram.Amulti-threadedprogramisonethatcanhavemultipleflowsofcontrolwhenexecuted.Atsometimeinstance,theremayexistmultipleinstructionsorexecutionpoints)thatarebeingexecutedintheprogramEx:inaWebbrowserwemaydothe
3、followingtasksatthesametime:1.scrollapage,2.downloadanappletorimage,3.playsound,4printapage.Athreadisasinglesequentialflowofcontrolwithinaprogram.single-threadedvsmultithreadedprograms{A();A1();A2();A3();B1();B2();}{A();newThreads{{A1();A2();A3()};{B1();B2()}}}startedbyjavafrommain(S
4、tring[])startedbymainthreadstartedbyBthreadlifetimeofCthreadThreadecologyinajavaprogram2.DefineandlaunchajavathreadEachJavaRuntimethreadisencapsulatedinajava.lang.Threadinstance.Twowaystodefineathread:1.ExtendtheThreadclass2.ImplementtheRunnableinterface:packagejava.lang;publicinterf
5、aceRunnable{publicvoidrun();}StepsforextendingtheThreadclass:SubclasstheThreadclass;OverridethedefaultThreadmethodrun(),whichistheentrypointofthethread,likethemain(String[])methodinajavaprogram.Defineathread//Example:publicclassPrint2ConsoleextendsThread{publicvoidrun(){//run()istoat
6、hreadwhatmain()istoajavaprogramfor(intb=-128;b<128;b++)out.println(b);}…//additionalmethods,fields…}ImpementtheRunnableinterfaceifyouneedaparentclass://byextendingJTextAreawecanreuseallexistingcodeofJTextAreapublicclassPrinter2GUIextendJTextAreaimplementRunnable{publicvoidrun(){for(i
7、ntb=-128;b<128;b++)append(Integer.toString(b)+“”);}}Howtolaunchathreadcreateaninstanceof[asubclassof]ofThread,saythread.Threadthread=newPrint2Console();Threadthread=newThread(newPrint2GUI(..));2.callitsstart()method,thread.start();.//note:notcallrun()!!Ex:Printer2Consolet1=newPrint
8、2Console();/
此文档下载收益归作者所有
点击更多查看相关文章~~