Java Thread

Preview:

DESCRIPTION

Java Thread for beginners

Citation preview

Java

Thread

Mul$tasking

•  Mul$taskingallowsseveralac$vi$estooccurconcurrentlyonthecomputer

•  Levelsofmul$tasking:– Process-basedmul1tasking

•  Allowsprograms(processes)torunconcurrently

– Thread-basemul1tasking(mul1threading)•  Allowspartsofthesameprocess(threads)torunconcurrently

2

Mul$tasking

•  Advantagesofmul$threadingoverprocess-basedmul$tasking–  Threadssharethesameaddressspace–  Contextswitchingbetweenthreadsisusuallyinexpensive–  Communica$onbetweenthreadisusuallyinexpensive

•  Javasupportsthread-basedmul/taskingandprovideshigh-levelfacili$esformul/threadedprogramming

3

MainThread

•  WhenaJavaprogramstartsup,onethreadbeginsrunningimmediately

•  Thisiscalledthemainthreadoftheprogram•  Itisthethreadfromwhichthechildthreadswillbespawned

•  OJen,itmustbethelastthreadtofinishexecu$on

4

MainThread

5

HowtocreateThread

1.  Byimplemen$ngRunnableInterface2.  ByextendingtheThreadclassitself•  Implemen'ngRunnable–  Needtoimplementthepublicvoidrun()method

•  ExtendingThread–  Needtooverridethepublicvoidrun()method

•  WhichoneisbeSer?

6

Implemen$ngRunnable

7

ExtendingThread

8

Mul$pleThreads

•  Itispossibletocreatemorethanonethreadinsidethemain

•  Inmul$plethreads,oJenyouwillwantthemainthreadtofinishlast.Thisisaccomplishedby–  usingalargedelayinthemainthread–  usingthejoin()method

•  WhetherathreadhasfinishedornotcanbeknownusingisAlive()method

•  Example:Mul'pleThreads.java,JoinAliveThreads.java

9

Thread States

10

ThreadPool

•  ThreadPoolsareusefulwhenyouneedtolimitthenumberofthreadsrunninginyourapplica$on–  Performanceoverheadstar$nganewthread–  Eachthreadisalsoallocatedsomememoryforitsstack

•  Insteadofstar$nganewthreadforeverytasktoexecuteconcurrently,thetaskcanbepassedtoathreadpool–  Assoonasthepoolhasanyidlethreadsthetaskisassignedtooneofthemandexecuted

11

ThreadPool

•  ThreadpoolsareoJenusedinmul$threadedservers–  Eachconnec$onarrivingattheserverviathenetworkiswrappedasataskandpassedontoathreadpool

–  Thethreadsinthethreadpoolwillprocesstherequestsontheconnec$onsconcurrently

•  JavaprovidesThreadPoolimplementa$onwithjava.u/l.concurrent.ExecutorService

12

ExecutorService

13

Synchroniza$on

•  Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethattheresourcewillbeusedbyonlyonethreadata$me

•  Theprocessbywhichthisisachievediscalledsynchroniza1on

•  Keytosynchroniza$onistheconceptofthemonitor•  Amonitorisanobjectthatisusedasamutuallyexclusivelock–  Onlyonethreadcanownamonitoratagiven$me

14

Synchroniza$on

•  Whenathreadacquiresalock,itissaidtohaveenteredthemonitor

•  AllotherthreadsaSemp$ngtoenterthelockedmonitorwillbesuspendedun$lthefirstthreadexitsthemonitor

•  Theseotherthreadsaresaidtobewai$ngforthemonitor

15

Synchroniza$on

•  Twowaytoachievesynchroniza$on.•  Synchronizedmethod

synchronizedvoidcall(Stringmsg){}•  Synchronizedblock

publicvoidrun(){ synchronized(target){target.call(msg);}}

•  Example:SynchronizedBlock.java,SynchronizedMethod.java,Synchroniza'onLock.java

16

InterThreadCommunica$on

•  Onewayistousepolling–  aloopthatisusedtochecksomecondi$onrepeatedly–  Oncethecondi$onistrue,appropriateac$onistaken

•  Javaincludesanelegantinterthreadcommunica$onmechanismviathewait(),no1fy()andno1fyAll()methods

•  ThesemethodsareimplementedasfinalmethodsinObject,soallclasseshavethem

•  Allthreemethodscanbecalledonlyfromwithinasynchronizedmethod

17

InterThreadCommunica$on•  wait()–  tellsthecallingthreadtogiveupthemonitorandgotosleepun$lsomeotherthreadentersthesamemonitorandcallsno$fy()

•  no/fy()–  wakesupthefirstthreadthatcalledwait()onsameobject

•  no/fyAll()–  wakesupallthethreadsthatcalledwait()onsameobject.Thehighestprioritythreadwillrunfirst

•  Example:IncorrectPC.java,CorrectPC.java,PCBlockingQueue.java

18

Suspend,ResumeandStop

•  Suspend–  Threadt;t.suspend();

•  Resume–  Threadt;t.resume();

•  Stop–  Threadt;t.stop();–  Cannotberesumedlater

•  suspendandstopcansome$mescauseserioussystemfailures

•  Example:SuspendResume.java19

Recommended