资源描述:
《java教程_线程入门(java tutorial _ thread entry)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、java教程_线程入门(Javatutorial_threadentry)Javatutorial_threadentryThreadisembeddedfeaturesofJava,thethreadisnoteasytomaster,therearebooksdedicatedtoJavathreads,readerscanreferto.Thus,theimportanceofJavathread,thisarticlewillintroducethebasicknowledgeofthethread.Sometimesyoum
2、ightwanttowriteaprogramthatexecutestasksatintervals,andyoucanuseTimerandTimerTaskatthistime,whichisveryconvenient.Youcanrefertohere.TherearetwowaystoimplementathreadinJava,thefirstistoimplementtherun()methodoftheRunnableinterface,andthesecondistoinherittheThreadclassand
3、overrideitsrun()method.Hereisthecodeexample:PublicclassDoSomethingimplementsRunnable{Publicvoidrun(){Iswhereyoudosomething//here}}PublicclassDoAnotherThingextendsThread{Publicvoidrun(){Iswhereyoudosomething//here}}Thedifferencebetweenthetwomethodsisthatifyourclasshasinh
4、eritedotherclasses,thenyoucanonlychoosetoimplementtheRunnableinterface,becauseJavaonlyallowssingleinheritance.ThreadsinJavahavefourstates:run,ready,hang,end.Ifathreadisfinished,itmeansthatheisadeadthread.Whenyoucallathread(start)whenthemethod,whenthethreadenterstheready
5、state,attentionisnotrunning,whentherunningtimeofthevirtualmachinetoassignhimCPUpieceofthreadbegantoenterthestate,whenthethreadentersthewaitingstate,forexample,whenwaitingforanevent.Whenthethreadisinasuspendedstate.Tostartathread,youonlyneedtocallthestart()method,andther
6、earetwowaystostartthethreadforthetwothreadimplementationmethods,asfollows:DoSomethingdoIt=newDoSomething();ThreadmyThread=newThread(doIt);MyThread.start();DoAnotherThingdoIt=newDoAnotherThing();DoIt.start();Becauseofthesecurityandotherfactors,thestop(Thread)methodhasnot
7、beenrecommended,soifyouwanttostopathread,youcansetasemaphore,forexample:PublicclassMyThreadimplementsRunnable{PrivateBooleanquit=false;Publicvoidrun(){While(...Quit){Do//something}}Publicvoidquit(){Quit=true;}}Ifeachthreadonlydoityourself,thenitisverysimple,butsometimes
8、severalthreadsmaybeaccessedatthesametimeanobjectandmaymodifyit,thistimeyoumustusethreadsynchronizationmethodor