[PDF] advanced numerical analysis nptel
[PDF] advanced numerology pdf
[PDF] advanced oops concepts in java pdf
[PDF] advanced oracle pl/sql developer's guide pdf
[PDF] advanced oracle sql programming the expert guide to writing complex queries pdf
[PDF] advanced oracle sql queries examples with answers
[PDF] advanced oracle sql queries for practice
[PDF] advanced oracle sql queries interview questions
[PDF] advanced oracle sql tuning burleson pdf
[PDF] advanced oracle sql tuning pdf download
[PDF] advanced oracle sql tuning pdf free download
[PDF] advanced oracle sql tuning the definitive reference pdf
[PDF] advanced oracle sql tuning the definitive reference pdf free download
[PDF] advanced oracle sql tutorial
[PDF] advanced php book pdf
Introductionto Javathreads
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Tableof Contents
Ifyou're viewingthisdocument online,youcan clickanyof thetopicsbelow tolinkdirectly tothatsection.
1.About thistutorial.......................................................2
2.Thread basics...........................................................3
3.A thread'slife............................................................8
4.Threads everywhere...................................................13
5.Sharing accesstodata ................................................16
6.Synchronization details................................................22
7.Additional threadAPIdetails .........................................26
8.Wrapup andresources................................................28
Introductionto JavathreadsPage 1of30
Section1. Aboutthistutorial
Whatis thistutorialabout?
Thistutorial exploresthebasics ofthreads-- whattheyare, whytheyare useful,andhow to getstarted writingsimpleprograms thatusethem. Wewill alsoexplorethe basicbuildingblocks ofmoresophisticated threadingapplications-- howto exchangedatabetween threads,howto controlthreads,and howthreadscan communicatewith eachother.
ShouldI takethistutorial?
Thistutorial isforJava programmerswhohave agoodworking knowledgeofthe Java language,but whohavelimited experiencewithmultithreading orconcurrency. Atthe completionofthis tutorial,youshould beableto writesimpleprograms thatuse threads.You shouldalsobe abletoread andunderstandprograms thatusethreads in straightforwardways.
Aboutthe author
BrianGoetz isaregular columnistonthe developerWorksJavatechnology zoneandhas beena professionalsoftwaredeveloper forthepast 15years.He isaPrincipal Consultantat Quiotix,a softwaredevelopmentand consultingfirmlocated inLosAltos, California. SeeBrian's publishedand upcomingarticlesinpopular industrypublications.
ContactBrian atbrian@quiotix.com.
ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials
Page2 of30Introduction toJavathreads
Section2. Threadbasics
Whatare threads?
Nearlyevery operatingsystemsupports theconceptof processes--independently running programsthat areisolatedfrom eachotherto somedegree. Threadingis afacilityto allowmultipleactivities tocoexistwithin asingleprocess. Most modernoperating systemssupportthreads, andtheconcept ofthreadshas beenaroundin variousforms formanyyears. Javaisthe firstmainstreamprogramming languageto explicitlyinclude threadingwithinthe languageitself,rather thantreatingthreading asa facilityof theunderlyingoperating system. Threadsare sometimesreferredto aslightweightprocesses .Like processes,threadsare independent,concurrent pathsofexecution throughaprogram, andeachthread hasitsown stack,its ownprogramcounter, anditsown localvariables.However, threadswithina processare lessinsulatedfrom eachotherthan separateprocessesare. Theyshare memory,file handles,andother per-processstate. Aprocess cansupportmultiple threads,whichappear toexecutesimultaneously and asynchronouslyto eachother.Multiple threadswithina processsharethe samememory addressspace, whichmeansthey haveaccessto thesamevariables andobjects,and they allocateobjects fromthesame heap.Whilethis makesiteasy forthreadsto share informationwith eachother,you musttakecare toensurethat theydonot interferewithother threadsin thesameprocess. TheJava threadfacilityand APIisdeceptively simple.However,writing complexprograms thatuse threadingeffectivelyis notquiteas simple.Becausemultiple threadscoexistin the samememory spaceandshare thesamevariables, youmusttake caretoensure thatyour threadsdon't interferewitheach other.
EveryJava programusesthreads
EveryJava programhasat leastonethread --themain thread.Whena Javaprogramstarts, theJVM createsthemain threadandcalls theprogram'smain()methodwithin thatthread. TheJVM alsocreatesother threadsthatare mostlyinvisibleto you--for example,threads associatedwith garbagecollection,object finalization,andother JVMhousekeepingtasks. Otherfacilities createthreadstoo, suchasthe AWT(AbstractWindowing Toolkit)orSwing UItoolkits, servletcontainers,application servers,andRMI (RemoteMethodInvocation).
Whyuse threads?
Thereare manyreasonsto usethreadsin yourJavaprograms. Ifyouuse Swing,servlets, RMI,or EnterpriseJavaBeans(EJB) technology,youmay alreadybeusing threadswithout realizingit. Someof thereasonsfor usingthreadsare thattheycan helpto: Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Introductionto JavathreadsPage 3of30
·Makethe UImoreresponsive
·Takeadvantage ofmultiprocessorsystems
·Simplifymodeling
·Performasynchronous orbackgroundprocessing
Moreresponsive UI
Event-drivenUI toolkits,suchas AWTandSwing, haveanevent threadthatprocesses UI eventssuch askeystrokesand mouseclicks. AWTand Swingprogramsattach eventlistenersto UIobjects.These listenersarenotified whena specificeventoccurs, suchasa buttonbeingclicked. Eventlistenersare calledfrom withinthe AWTeventthread. Ifan eventlistenerwere toperforma lengthytask,such ascheckingspelling inalarge document,the eventthreadwould bebusyrunning thespellingchecker, andthuswould not beable toprocessadditional UIeventsuntil theeventlistener completed.Thiswould make theprogram appeartofreeze, whichisdisconcerting totheuser. Toavoid stallingtheUI, theeventlistener shouldhandoff longtasksto anotherthreadso thatthe AWTthreadcan continueprocessingUI events(includingrequests tocancelthe long-runningtask beingperformed)while thetaskis inprogress.
Takeadvantage ofmultiprocessorsystems
Multiprocessor(MP) systemsaremuch morecommonthan theyusedto be.Oncethey were foundonly inlargedata centersandscientific computingfacilities.Now manylow-endserver systems-- andevensome desktopsystems-- havemultipleprocessors. Modernoperating systems,includingLinux, Solaris,andWindows NT/2000,cantake advantageof multipleprocessorsand schedulethreadsto executeonany available processor. Thebasic unitofscheduling isgenerallythe thread;ifa programhasonly oneactivethread, itcan onlyrunon oneprocessorat atime.If aprogramhas multipleactivethreads, then multiplethreads maybescheduled atonce.In awell-designedprogram, usingmultiple threadscan improveprogramthroughput andperformance.
Simplicityof modeling
Insome cases,usingthreads canmakeyour programssimplerto writeandmaintain. Considera simulationapplication,where yousimulatethe interactionbetweenmultiple entities.Giving eachentityits ownthreadcan greatlysimplifymany simulationandmodeling applications. Anotherexample whereitis convenienttouse separatethreadsto simplifyaprogram is whenan applicationhasmultiple independentevent-drivencomponents. forexample,an applicationmight haveacomponent thatcountsdown thenumberof secondssincesome ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials
Page4 of30Introduction toJavathreads
eventand updatesadisplay onthescreen. Ratherthanhaving amainloop checkthetime periodicallyand updatethedisplay, itismuch simpler--and lesserror-prone-- tohavea threadthat doesnothingbut sleepuntila certainamountof timehaselapsed andthen updatethe on-screencounter.This waythemain threaddoesn'tneed toworryabout the timerat all.
Asynchronousor backgroundprocessing
Serverapplications gettheirinput fromremotesources, suchassockets. Whenyouread froma socket,ifthere isnodata currentlyavailable,the callto SocketInputStream.read()willblock untildatais available. Ifa single-threadedprogramwere toreadfrom thesocket,and theentityon theotherend of thesocket wereneverto sendanydata, theprogramwould simplywaitforever, andnoother processingwould getdone.On theotherhand, theprogramcould pollthesocket toseeif datawas available,butthis isoftenundesirable forperformancereasons. If,instead, youcreateda threadtoread fromthesocket, themainthread couldperformother taskswhile theotherthread waitedforinput fromthesocket. Youcaneven createmultiple threadsso youcanread frommultiplesockets atonce.In thisway,you arenotifiedquickly whendata isavailable(because thewaitingthread isawakened)without havingtopoll frequentlyto checkifdata isavailable.The codetowait onasocket usingthreadsis also muchsimpler andlesserror-prone thanpollingwould be.
Simple,but sometimesrisky
Whilethe Javathreadfacility isveryeasy touse,there areseveralrisks youshouldtry to avoidwhen youcreatemultithreaded programs. Whenmultiple threadsaccessthe samedataitem, suchasa staticfield,an instancefieldof aglobally accessibleobject,or asharedcollection, youneedto makesurethat they coordinatetheir accesstothe datasothat bothseea consistentviewof thedataand neither stepson theother'schanges. TheJavalanguage providestwokeywords forthispurpose: synchronizedandvolatile.We willexplorethe useandmeaning ofthesekeywords laterin thistutorial. Whenaccessing variablesfrommore thanonethread, youmustensure thattheaccess is properlysynchronized. Forsimplevariables, itmaybe enoughtodeclare thevariable volatile,but inmostsituations, youwillneed tousesynchronization. Ifyou aregoingto usesynchronizationto protectaccessto sharedvariables,you mustmake sureto useiteverywhereinyour programwherethe variableisaccessed.
Don'toverdo it
Whilethreads cangreatlysimplify manytypesof applications,overuseof threadscanbe hazardousto yourprogram'sperformance anditsmaintainability. Threadsconsume resources.Therefore, thereisa limitonhow manythreadsyou cancreatewithout degrading Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Introductionto JavathreadsPage 5of30
performance. Inparticular, usingmultiplethreads willnotmakea CPU-boundprogramrun anyfasteron a single-processorsystem.
Example:Using athreadfor timinganda threadtodo
work Thefollowing exampleusestwo threads,onefor timingandone todoactual work.Themain threadcalculates primenumbersusing averystraightforward algorithm. Beforeit starts,itcreates andstartsa timerthread,which willsleepfor tenseconds,and then seta flagthatthe mainthreadwill check.Afterten seconds,themain threadwillstop. Note thatthe sharedflagis declaredvolatile. *CalculatePrimes --calculateas manyprimesas wecanin tenseconds publicclass CalculatePrimesextendsThread { publicstatic finalintMAX_PRIMES =1000000; publicstatic finalintTEN_SECONDS =10000; publicvolatile booleanfinished= false; publicvoid run(){ int[]primes =newint[MAX_PRIMES]; intcount =0; for(int i=2;count< MAX_PRIMES;i++){ //Check toseeif thetimerhas expired if(finished) { break; booleanprime =true; for(int j=0;j< count;j++){ if(i %primes[j]== 0){ prime= false; break; if(prime) { primes[count++]= i;
System.out.println("Foundprime: "+i);
publicstatic voidmain(String[]args) {
CalculatePrimescalculator =newCalculatePrimes();
calculator.start(); try{
Thread.sleep(TEN_SECONDS);
ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials
Page6 of30Introduction toJavathreads
catch(InterruptedException e){ //fall through calculator.finished= true;
Summary
TheJava languageincludesa powerfulthreadingfacility builtintothe language.Youcan use thethreading facilityto:
·Increasethe responsivenessofGUI applications
·Takeadvantage ofmultiprocessorsystems
·Simplifyprogram logicwhenthere aremultipleindependent entities ·Performblocking I/Owithoutblocking theentireprogram Whenyou usemultiplethreads, youmustbe carefultofollow therulesfor sharingdata betweenthreads, whichwe'llcover inSharingaccess todataonpage 16.All theserulesboil downto onebasicprinciple: Don'tforget tosynchronize. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Introductionto JavathreadsPage 7of30
Section3. Athread'slife
Creatingthreads
Thereare severalwaysto createathread inaJava program.EveryJava programcontains atleast onethread:the mainthread.Additional threadsarecreated throughtheThread constructoror byinstantiatingclasses thatextendthe Threadclass. Javathreads cancreateother threadsbyinstantiating aThreadobjectdirectly oranobject thatextends Thread.In theexamplein Threadbasics onpage 3,in whichwecalculated as manyprimes aswecould intenseconds, wecreateda threadbyinstantiating anobjectof typeCalculatePrimes,which extendsThread. Whenwe talkaboutthreads inJavaprograms, therearetwo relatedentitieswe maybe referringto: theactualthread thatisdoing theworkor theThreadobjectthat representsthe thread.The runningthreadis generallycreatedby theoperatingsystem; theThreadobject iscreated bytheJava VMasa meansofcontrolling theassociatedthread.
Creatingthreads andstartingthreads arenotthe same
Athread doesn'tactuallybegin toexecuteuntil anotherthreadcalls thestart()methodon theThreadobjectfor thenewthread. TheThreadobjectexists beforeitsthread actually starts,and itcontinuesto existafterits threadexits.This allowsyouto controlorobtain informationabout athreadyou've created,evenif thethreadhasn't startedyetor hasalready completed. It'sgenerally abadidea tostart()threadsfrom withinaconstructor. Doingsocould exposepartially constructedobjectsto thenewthread. Ifanobject ownsathread, thenit shouldprovide astart()orinit()methodthat willstartthe thread,ratherthan startingit fromthe constructor.(SeeResourcesonpage 28forlinks toarticlesthat provideamore detailedexplanation ofthisconcept.)
Endingthreads
Athread willendin oneofthree ways:
·Thethread comestothe endofits run()method.
·Thethread throwsanExceptionorErrorthatis notcaught. ·Anotherthread callsoneof thedeprecatedstop()methods.Deprecated meanstheystill exist,but youshouldn'tuse theminnew codeandshould strivetoeliminate themin existingcode. Whenall thethreadswithin aJavaprogram complete,theprogram exits. ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials
Page8 of30Introduction toJavathreads
Joiningwith threads
TheThread APIcontainsa methodforwaiting foranotherthread tocomplete:the join() method.When youcallThread.join(),the callingthreadwill blockuntilthe targetthread completes. Thread.join()isgenerally usedbyprograms thatusethreads topartitionlarge problems intosmaller ones,givingeach threadapiece oftheproblem. Theexampleat theendof this sectioncreates tenthreads,starts them,thenuses Thread.join()towait forthemall to complete.
Scheduling
Exceptwhen usingThread.join()andObject.wait(),the timingofthread scheduling andexecution isnondeterministic.If twothreadsare runningatthe sametimeand neitheris waiting,you mustassumethat betweenanytwo instructions,otherthreads mayberunning andmodifying programvariables.If yourthreadwill beaccessingdata thatmaybe visibleto otherthreads, suchasdata referenceddirectlyor indirectlyfromstatic fields(global variables),you mustusesynchronization toensuredata consistency. Inthe simpleexamplebelow, we'llcreateand starttwothreads, eachofwhich printstwo linesto System.out: publicclass TwoThreads{ publicstatic classThread1extends Thread{ publicvoid run(){
System.out.println("A");
System.out.println("B");
publicstatic classThread2extends Thread{ publicvoid run(){
System.out.println("1");
System.out.println("2");
publicstatic voidmain(String[]args) { newThread1().start(); newThread2().start(); Wehave noideain whatorderthe lineswillexecute, exceptthat"1" willbeprinted before"2" and"A" before"B."The outputcouldbe anyoneof thefollowing:
·12 AB
·1A 2B
·1A B2
·A1 2B
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Introductionto JavathreadsPage 9of30
·A1 B2
·AB 12
Notonly maytheresults varyfrommachine tomachine,but runningthesame program multipletimes onthesame machinemayproduce differentresults.Never assumeonethread willdo somethingbeforeanother threaddoes,unless you'veusedsynchronization toforcea specificordering ofexecution.
Sleeping
TheThread APIincludesa sleep()method,which willcausethe currentthreadto gointoa waitstate untilthespecified amountoftime haselapsedor untilthethread isinterruptedby anotherthread callingThread.interrupt()onthe currentthread'sThreadobject.When thespecified timeelapses,the threadagainbecomes runnableandgoes backontothe scheduler'squeue ofrunnablethreads. Ifa threadisinterrupted byacall toThread.interrupt(),the sleepingthreadwill throw anInterruptedExceptionsothat thethreadwill knowthatit wasawakenedby an interruptand won'thaveto checktosee ifthetimer expired. TheThread.yield()methodis likeThread.sleep(),but insteadofsleeping, itsimply pausesthe currentthreadmomentarily sothatother threadscanrun. Inmost implementations,threads withlowerpriority willnotrun whenathread ofhigherpriority calls
Thread.yield().
TheCalculatePrimesexampleused abackgroundthread tocalculateprimes, thenslept forten seconds.Whenthe timerexpired,it setaflag toindicatethat thetenseconds had expired.
Daemonthreads
Wementioned thataJava programexitswhen allofits threadshavecompleted, butthisis notexactly correct.Whatabout thehiddensystem threads,suchas thegarbagecollection threadand otherscreatedby theJVM?We havenoway ofstoppingthese. Ifthosethreads arerunning, howdoesany Javaprogramever exit? Thesesystem threadsarecalled daemonthreads.A Javaprogramactually exitswhenall its non-daemonthreads havecompleted. Anythread canbecomea daemonthread.You canindicatea threadisa daemonthreadby callingthe Thread.setDaemon()method.You mightwantto usedaemonthreads for backgroundthreads thatyoucreate inyourprograms, suchastimer threadsorother deferredevent threads,whichare onlyusefulwhile thereareother non-daemonthreads running. Example:Partitioning alargetask withmultiplethreads Inthis example,TenThreadsshowsa programthatcreates tenthreads,each ofwhichdo ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials
Page10 of30Introduction toJavathreads
somework. Itwaitsfor themallto finish,thengathers theresults. *Creates tenthreadsto searchforthe maximumvalueof alargematrix. *Each threadsearchesone portionofthe matrix. publicclass TenThreads{ privatestatic classWorkerThreadextends Thread{ intmax =Integer.MIN_VALUE; int[]ourArray; publicWorkerThread(int[] ourArray){ this.ourArray= ourArray; //Find themaximumvalue inourparticular pieceofthe array publicvoid run(){ for(int i=0; i
WorkerThread[]threads =newWorkerThread[10]; int[][]bigMatrix =getBigHairyMatrix(); intmax =Integer.MIN_VALUE; //Give eachthreada sliceofthe matrixtowork with for(int i=0;i< 10;i++){ threads[i]= newWorkerThread(bigMatrix[i]); threads[i].start(); //Wait foreachthread tofinish try{ for(int i=0;i< 10;i++){ threads[i].join(); max= Math.max(max,threads[i].getMax()); catch(InterruptedException e){ //fall through System.out.println("Maximumvalue was"+ max);
Summary
Likeprograms, threadshavea lifecycle:they start,theyexecute, andtheycomplete. One program,or process,maycontain multiplethreads,which appeartoexecute independently ofeach other. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks Introductionto JavathreadsPage 11of30
Athread iscreatedby instantiatingaThreadobject,or anobjectthat extendsThread,but thethread doesn'tstartto executeuntilthe start()methodis calledonthe newThread object.Threads endwhenthey cometothe endoftheir run()methodor throwan unhandledexception. Thesleep()methodcan beusedto waitfora certainamountof time;thejoin()method canbe usedtowait untilanotherthread completes. ibm.com/developerWorksPresentedby developerWorks,yoursource forgreattutorials Page12 of30Introduction toJavathreads
Section4. Threadseverywhere
Whocreates threads?
Evenif youneverexplicitly createanew thread,youmay findyourselfworking withthreads anyway.Threads areintroducedinto ourprogramsfrom avarietyof sources. Thereare anumberof facilitiesandtools thatcreatethreads foryou,and youshould understandhow threadsinteractand howtoprevent threadsfromgetting intheway ofeach otherif you'regoingto usethesefacilities. AWTand Swing
Anyprogram thatusesAWT orSwingmust dealwiththreads. TheAWTtoolkit createsa singlethread forhandlingUI events,andany eventlistenerscalled byAWTevents execute inthe AWTeventthread. Notonly doyouhave toworryabout synchronizingaccessto dataitemsshared between eventlisteners andotherthreads, butyouhave tofinda wayforlong-running taskstriggered byevent listeners--such ascheckingspelling inalarge documentorsearching afilesystem fora file--to runina backgroundthreadso theUIdoesn't freezewhilethe taskisrunning (whichwould alsopreventthe userfromcanceling theoperation).A goodexampleof a frameworkfor doingthisis theSwingWorkerclass(see Resourcesonpage 28). TheAWT eventthreadis notadaemon thread;thisis whySystem.exit()isoften usedto endAWT andSwingapps. UsingTimerTask
TheTimerTaskfacilitywas introducedtothe Javalanguagein JDK1.3.This convenient facilityallows youtoexecute ataskat alatertime (thatis,for example,runa taskonceten secondsfrom now),orto executeatask periodically(thatis, runatask everytenseconds). Implementingthe Timerclassis quitestraightforward:it createsatimer threadandbuilds a queueof waitingeventssorted byexecutiontime. TheTimerTaskthreadis markedasa daemonthreadso itdoesn'tprevent theprogram fromexiting. Becausetimer eventsexecutein thetimerthread, youmustmake surethataccess toany dataitems usedfromwithin atimertask isproperlysynchronized. Inthe CalculatePrimesexample,instead ofhavingthe mainthreadsleep, wecouldhave useda TimerTaskasfollows: publicstatic voidmain(String[]args) { Timertimer =newTimer();
finalCalculatePrimes calculator=new CalculatePrimes(); Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks Introductionto JavathreadsPage 13of30
calculator.start(); timer.schedule( newTimerTask() { publicvoid run() calculator.finished= true; },TEN_SECONDS); Servletsand JavaServerPagestechnology
Servletcontainers createmultiplethreads inwhichservlet requestsareexecuted. Asthequotesdbs_dbs14.pdfusesText_20