Вы находитесь на странице: 1из 23

!

ava 1hreads


!"#$"%&%'(# *#+,#""-+.- - /01."02345%
arallel and ulsLrlbuLed rogrammlng


2013-2014

Aer Lhls class you wlll be able Lo.
undersLand whaL ls a 1hread.
Pow Lo sLarL several Lhreads.
1he maln meLhods of Lhe 1hread class.
lnLerrupuon of Lhreads.
1he llfe cycle of a Lhread.
WhaL are Lhreads?

! 1he llLeral Lranslauon: !"#$%

! SLands for 1hread of ConLrol", a secuon of Lhe
code LhaL runs lndependenLly from oLher
sequenual secuons ln Lhe same program
Why muluple Lhreads?
! lf, ln a program, we can use several Lhreads:
! for long calculauons,
! for LexL lnpuL
! for spell checklng
Lhe program can execuLe all 3 Lasks concurrenLly so
we can wrlLe Lhe LexL whlle Lhe calculauon ls belng
done and LexL ls belng correcLed.

! lL seems LhaL all ls happenlng aL Lhe same ume.
Pow are Lhreads execuLed?
Lxecuuon of Lhe dlerenL Lhreads can occur ln
Lhree scenarlos:
! 1hey execuLe ln parallel, lf Lhere ls more
Lhan one processor
! 1hey can run lnLerleaved on one processor
! 1hey can run ln a mlxed parallel/
lnLerleaved soluuon

MuluLasklng vs. MuluLhreadlng
! 6378.%190+$: A process (ex. an appllcauon) runs ln a
'()%*%+( address space. Muluple processes can be
runnlng aL Lhe same ume, buL one process cannoL
manlpulaLe Lhe memory allocaLed Lo anoLher process.
! 6378.:"-%50+$: A process can creaLe muluple
Lhreads LhaL all execuLe ln Lhe '%,( address space.
1hls means LhaL all Lhreads poLenually have access Lo
Lhe same lnsLances of ob[ecLs, le descrlpLors,
neLwork connecuon and so on.

MuluLasklng
Multithreading
lmporLanL dlerences beLween
processes and Lhreads
! Creaung a Lhread requlres less resources Lhan creaung a
process.
! A process usually requlres Lhe operauon sysLem Lo creaLe and
malnLaln a comprehenslve low-level daLa sLrucLure lncludlng a
vlrLual memory map, le descrlpLors, user ldenucauon, eLc.
! 1he Lhreads for a process all share Lhe daLa sLrucLure for Lhe
process and are Lherefore more hlgh-level enuues. 1hey
requlre llule more Lhan a Lhelr own sLack.
! 1hreads exlsL lnslde a process - all processes have aL leasL
one Lhread. All Lhreads share Lhe resources of Lhe process,
lncludlng memory, le descrlpLors and so on, whlch makes
communlcauon beLween Lhreads more emclenL - buL
poLenually problemauc.
Muluhreadlng ln !AvA
1. Lvery Lhread sLarLs execuuon ln a speclc locauon:
l. lor Lhe rsL Lhread, Lhls locauon ls Lhe publlc sLauc
meLhod maln()
ll. SubsequenL Lhreads sLarL ln a locauon declded by
Lhe developer.
2. Lvery Lhread execuLes lndependenLly of Lhe oLher
Lhreads ln Lhe program, however, Lhere exlsL
varlous mechanlsms LhaL allow Lhreads Lo
cooperaLe.
WhaL can Lhreads be used for?
! Craphlcal lnLerfaces
! More performance
! 1he processor(s) are less ldle
- When one Lhread ls walung, for lnsLance readlng
daLa from a hard drlve, anoLher Lhread can
compuLe.
! ulerenL Lasks, for lnsLance Lwo anlmauons runnlng
aL Lhe same ume.
! Allows for muluple processors/cores Lo be uullzed
aL Lhe same ume.

1hreads ln !AvA
public class OMeuThread extends Thread {




public void run() {
System.out.println("o meu thread");
}


public static void main(String [] argv) {
Thread t = new OMeuThread();
t.start();
}
}
1he second Lhread ls expllclLly sLarLed by Lhe
programmer and execuuon sLarLs ln Lhe run meLhod
Second Lhread LermlnaLes when leavlng Lhe run
meLhod
1he rsL Lhread ends when leavlng Lhe maln meLhod
Class 1hread
! Lvery Lhread ls assoclaLed Lo an lnsLance of Lhe
class 1hread
! An appllcauon LhaL creaLes one or more Lhreads,
provldes Lhe code Lo for Lhose Lhreads.
! ... Lhere are Lwo ways of speclfylng Lhe code
llke on Lhe prevlous sllde, by exLendlng Lhe class
;:"-%5
by lmplemenung Lhe <3++%27- lnLerface

uslng Lhe 8unnable lnLerface
public class OMeuThread implements Runnable{

public void run() {
System.out.println("o meu thread");
}

public static void main(String [] argv) {
Runnable omt = new OMeuThread();
Thread t = new Thread(omt);
t.start();
}
}
1hread.sleep,
! "Sleep" ls a sLauc meLhod LhaL pauses Lhe execuuon of
Lhe calllng Lhread for a speclc perlod of ume
! 1hls leaves more ume for oLher Lhreads and processes
Lo execuLe
! Sleep umes can be specled ln mllllseconds and ln
nanoseconds, buL Lhere ls no guaranLee LhaL Lhe Lhread
ls paused for exacLly Lhe ume specled. lL depends on
Lhe CS, on Lhe hardware and on Lhe resources
currenLly avallable.
! sleep can Lhrow an lnLerrupLedLxcepuon when anoLher
Lhread lnLerrupLs a sleeplng Lhread


1hread.sleep,


WhaL ls Lhe resulL of Lhe followlng program?


1hread.sleep, 1hread.currenL1hread
and Lhe lnLerrupL meLhod
/ 1/10/2007 - Adaptado do JAVA Tutorial por Nuno David
public class SleepMessages extends Thread {
public void run() {
String importantInfo[] = { "Mares eat oats", "Does eat oats",
"Little lambs eat ivy", "A kid will eat ivy too" };

for (int i = 0; i < importantInfo.length; i++) {
try {
// Pause for 4 seconds
System.out.println(currentThread() + ": sleep for 4 seconds");
sleep(4000);
// Print a message
System.out.println("\t" + importantInfo[i]);
} catch (InterruptedException e) {
System.out.println(currentThread() + ": Ops! I was interrupted!");
}
}
}
public static void main(String args[]) throws InterruptedException {
Thread t = new SleepMessages();
t.start();
int pausa = (new Random()).nextInt(16000);
System.out.println(currentThread() + ": sleep for " + pausa / 1000 + " seconds");
sleep(pausa);
t.interrupt();
}
}

Thread[main,5,main]: sleep for 5 seconds
Thread[Thread-0,5,main]: sleep for 4 seconds
Mares eat oats
Thread[Thread-0,5,main]: sleep for 4 seconds
Thread[Thread-0,5,main]: Ops! I was
interrupted!
Thread[Thread-0,5,main]: sleep for 4 seconds
Little lambs eat ivy
Thread[Thread-0,5,main]: sleep for 4 seconds
A kid will eat ivy too
Exit code: 0
No Errors
lnLerrupuon of Lhreads - example
of console ouLpuL
lnLerrupuon of Lhreads
! =+ 0+.-""3>8#+ 5#-1 +#. 1.#> % .:"-%5 #" >%31- 0.?
! When a Lhread ls lnLerrupLed, a ag ls seL Lo lndlcaLe LhaL Lhe
Lhread ls now ln an lLerrupLed sLaLe
! An lnLerrupuon lndlcaLes LhaL someLhlng happened and LhaL
Lhe Lhread may need Lo do someLhlng dlerenL
! lL ls Lhe programmer who decldes how a Lhread should respond
Lo Lhe lnLerrupuon. 1hls lncludes decldlng lf a Lhread should
LermlnaLe when lnLerrupLed or noL
! lf a Lhread spends a loL of ume wlLhouL calllng a meLhod LhaL
Lhrows an lnLerrupLed excepuon, lL can check lf lL was
lnLerrupLed ln Lhe followlng way:

if (Thread.interrupted()){
// DO SOMETHING
throw new InterruptedException();
}
Calllng lnLerrupLed() clears
Lhe lnLerrupLed ag!
! t.stop() LermlnaLes a Lhread and frees Lhe monlLors LhaL
lL has conLrol over, AvClu uSlnC 1PlS ML1PCu. 1hreads
should LermlnaLe ln a conLrolled way ln order Lo avold
poLenual memory and loglcal lnconslsLencles, sLop() was
deprecaLed ln !uk 1.2
! t.suspend()/t.resume() suspend/resume a Lhread
L, Avold uslng Lhls as lL can creaLe -(%-./01'2 Lhese meLhods
were deprecaLed ln !uk 1.2
! t.isAlive() checks lf a Lhread ls acuve. Can only be
used Lo verlfy LhaL a Lhread has ended.
! t.join() allows for one Lhread Lo walL for anoLher Lhread
Lo end. Llke wlLh Lhe sleep() meLhod, an lnLerrupLedLxcepuon
can be Lhrown
lor more on Lhe problems of sLop, suspend and resume see:
Why are 1hread.sLop, 1hread.suspend and 1hread.resume ueprecaLed?
CLher meLhods on Lhe 1hread class
Llfe cycle of a 1hread
noL runnable when lL
ls sleeplng or walung.
L.yleld() - glves space Lo anoLher Lhread Lo execuLe.
1o sLudy
SLudy Lhe class 1hread ln Lhe !ava Al
SLudy Lhe 8unnable lnLerface ln Lhe !ava
Al
SLudy Lhe recommended blbllography
racucal exerclses
8lbllography

! !AvA 1uLorlal
hup://download.oracle.com/[avase/LuLorlal/essenual/concurrency/lndex.hLml
! !AvA 1hreads, C'8ellly, chapLers 1-2
! MuluLhreaded, arallel, and ulsLrlbuLed
rogrammlng, C.8. Andrews, chapLer 1-2
! MuluLhreaded rogrammlng, Lewls & 8erg,
chapLers 1-4

Summary
1hreads ln !AvA
1he 1hread concepL - muluLasklng vs. muluLhreadlng
1he 1hread class
SLarung Lhreads - Lhe 8unnable lnLerface
lnLerrupuons
CLher meLhods on Lhe class 1hread
A Lhreads llfe-cycle
Lxerclses

Вам также может понравиться