Java Unit-3
Java Unit-3
t-
3
Except
ionHandl
i
ngi
nJav
a
Thepr
ocessofconv
ert
ingsy
stem er
rormessagesi
ntouserf
ri
endl
yer
rormessagei
s
knownasExcept
ionhandl
i
ng.Thi
sisoneoft
hepower
fulf
eat
ureofJav
atohandl
e
r
unt
imeer
rorandmai
ntai
nnor
mal
flowofj
avaappl
i
cat
ion.
Except
ion
AnExcept
ioni
sanev
ent
,whi
choccur
sdur
ingt
heexecut
ionofapr
ogr
am,t
hat
di
srupt
sthenor
mal
flowoft
hepr
ogr
am'
sInst
ruct
ions.
WhyuseExcept
ionHandl
i
ng
Handl
i
ngt
heexcept
ioni
snot
hingbutconv
ert
ingsy
stem er
rorgener
atedmessage
i
nto userf
ri
endl
y er
rormessage.Whenev
eran except
ion occur
sint
he j
ava
appl
i
cat
ion,JVM wi
l
lcr
eat
eanobj
ectofappr
opr
iat
eexcept
ionofsubcl
assand
gener
ates sy
stem er
rormessage,t
hese sy
stem gener
ated messages ar
e not
under
standabl
ebyusersoneedt
oconv
erti
tint
ouserf
ri
endl
yer
rormessage.You
can conv
ertsy
stem er
rormessage i
nto userf
ri
endl
yer
rormessage byusi
ng
except
ionhandl
i
ngf
eat
ureofj
ava.
ForExampl
e:wheny
oudi
vi
deanynumberbyz
erot
hensy
stem gener
ate/byzer
oso
t
hisi
snotunder
standabl
ebyusersoy
oucanconv
ertt
hismessagei
ntouserf
ri
endl
y
er
rormessagel
i
keDon'
tent
erzer
ofordenomi
nat
or.
Hi
erar
chyofExcept
ioncl
asses
Ty
peofExcept
ion
1.
CheckedExcept
ion
2.
Un-
CheckedExcept
ion
1.
CheckedExcept
ion
Checked Except
ionar
ethe except
ion whi
ch checked atcompi
l
e-t
ime.These
except
ionar
edi
rect
lysub-
classofj
ava.
lang.
Except
ioncl
ass.
Onl
yforr
emember
:Checkedmeanscheckedbycompi
l
ersocheckedexcept
ionar
e
checkedatcompi
l
e-t
ime.
2.
Un-
CheckedExcept
ion
Un-
CheckedExcept
ionar
etheexcept
ionbot
hident
if
iesorr
aisedatr
unt
ime.These
except
ionar
edi
rect
lysub-
classofj
ava.
lang.
Runt
imeExcept
ioncl
ass.
Not
e:I
nreal
timeappl
i
cat
ionmost
lywecanhandl
eun-
checkedexcept
ion.
Onl
yforr
emember
:Un-
checked meansnotchecked bycompi
l
erso un-
checked
except
ionar
echeckedatr
un-
ti
menotcompi
l
eti
me.
Di
ff
erencebet
weencheckedExcept
ionandun-
checkedExcept
ion
CheckedExcept
ion Un-
CheckedExcept
ion
checkedExcept
ionar
echeckedat un-
checkedExcept
ionar
echeckedatr
un
1
compi
l
eti
me t
ime
e.
g. e.
g.
3 Fi
l
eNot
FoundExcept
ion, Ar
it
hmet
icExcept
ion,Nul
l
Poi
nter
Except
ion,
Number
Not
FoundExcept
ionet
c. Ar
ray
IndexOut
OfBoundsExcept
ionet
c.
Di
ff
erencebet
weenEr
rorandExcept
ion
Er
ror Except
ion
1 Can'
tbehandl
e. Canbehandl
e.
Exampl
e: Exampl
e:
2 NoSuchMet
hodEr
ror Cl
assNot
FoundExcept
ion
Out
OfMemor
yEr
ror Number
For
mat
eExcept
ion
UncaughtExcept
ions(
wit
houtusi
ngt
ry&cat
ch)
:
Exampl
ewi
thoutExcept
ionHandl
i
ng
classExcept i
onDemo
{
publicstaticv oidmain(St
ri
ng[]args)
{
i
nta=10, ans=0;
ans=a/ 0;
Sy st
em. out.printl
n("
Denominatornotbezero"
);
}
}
Abnor
mal
l
yt erminatepr ogr am andgi
veamessagel i
kebelow,t
hiser
rormessagei
s
notunder
standabl
ebyusersoweconv
ertt
hiser
rormessagei
ntouserf
ri
endl
yer
ror
message,
li
ke"
denomi
nat
ornotbezer
o".
Handl
i
ngt
heExcept
ion
Handl
i
ngt
heexcept
ioni
snot
hingbutconv
ert
ingsy
stem er
rorgener
atedmessage
i
ntouserf
ri
endl
yer
rormessagei
not
her
swor
dwhenev
eranexcept
ionoccur
sint
he
j
avaappl
i
cat
ion,
JVM wi
l
lcr
eat
eanobj
ectofappr
opr
iat
eexcept
ionofsubcl
assand
gener
ates sy
stem er
rormessage,t
hese sy
stem gener
ated messages ar
e not
under
standabl
ebyusersoneedt
oconv
erti
tint
ouser
-f
ri
endl
yer
rormessage.You
can conv
ertsy
stem er
rormessage i
nto user
-f
ri
endl
y er
rormessage by usi
ng
except
ionhandl
i
ngf
eat
ureofj
ava.
UseFi
vekey
wor
dsf
orHandl
i
ngt
heExcept
ion
1.
tr
y
2.
cat
ch
3.
fi
nal
l
y
4.
thr
ows
5.
thr
ow
Sy
ntaxf
orhandl
i
ngt
heexcept
ion:
tr
y
{
//stat
ementscausesproblem atrunt
ime
}
catch(t
ypeofexcept
ion-
1obj ect
-1)
{
//stat
ementsprovi
desuserf ri
endl
yerr
ormessage
}
catch(t
ypeofexcept
ion-
2obj ect
-2)
{
//stat
ementsprovi
desuserf ri
endl
yerr
ormessage
}
fi
nall
y
{
//stat
ementswhichwillexecutecompulsor
y
}
1.
tr
ybl
ock
I
nsi
det
rybl
ockwewr
it
ethebl
ockofst
atement
swhi
chcausesexecut
ionsatr
un
t
imei
not
herwor
dst
rybl
ockal
way
scont
ainspr
obl
emat
icst
atement
s.
I
mpor
tantpoi
ntsaboutt
rybl
ock
I
fanyexcept
ionoccur
sint
rybl
ockt
henCPUcont
rol
scomesoutt
othet
rybl
ock
andexecut
esappr
opr
iat
ecat
chbl
ock.
Af
terexecut
ingappr
opr
iat
ecat
chbl
ock,
event
hroughweuser
unt
imest
atement
,
CPUcont
rol
nev
ergoest
otr
ybl
ockt
oexecut
ether
estoft
hest
atement
s.
Eachandev
eryt
rybl
ockmustbei
mmedi
atel
yfol
l
owedbycat
chbl
ockt
hati
sno
i
nter
medi
atest
atement
sar
eal
l
owedbet
weent
ryandcat
chbl
ock.
Eachandev
eryt
rybl
ockmustcont
ainsatl
eastonecat
chbl
ock.Buti
tishi
ghl
y
r
ecommendedt
owr
it
emul
ti
plecat
chbl
ocksf
orgener
ati
ngmul
ti
pleuserf
ri
endl
y
er
rormessages.
Onet
rybl
ockcancont
ainsanot
hert
rybl
ockt
hati
snest
edori
nnert
rybl
ockcan
bepossi
ble.
2.
cat
chbl
ock
I
nsi
decat
chbl
ock we wr
it
ethe bl
ock ofst
atement
s whi
ch wi
l
lgener
ates user
f
ri
endl
yer
rormessages.
cat
chbl
ocki
mpor
tantpoi
nts
Cat
chbl
ockwi
l
lexecut
eexcept
ionoccur
sint
rybl
ock.
Youcanwr
it
emul
ti
plecat
chbl
ocksf
orgener
ati
ngmul
ti
pleuserf
ri
endl
yer
ror
messagest
omakey
ourappl
i
cat
ionst
rong.Youcanseebel
owexampl
e.
Atat
imeonl
yonecat
chbl
ockwi
l
lexecut
eoutofmul
ti
plecat
chbl
ocks.
i
n cat
ch bl
ock y
ou decl
are an obj
ectofsub cl
ass and i
twi
l
lbe i
nter
nal
l
y
r
efer
encedbyJVM.
Exampl
e:(
try
&cat
ch)
:
cl
assExcept i
onDemo
{
publi
cstaticv oidmain(St
ri
ng[]args)
{
i
nta=10, ans=0;
tr
y
{
ans=a/0;
}
catch(Exceptione)
{
System.out.print
ln(
"Denominatornotbezer
o")
;
}
}}
Out
put
Denomi
nat
ornotbezer
o
3.
thr
ow
t
hrow i
sakey
wor
dinj
aval
anguagewhi
ch i
sused t
othr
ow anyuserdef
ined
except
iont
othesamesi
gnat
ureofmet
hodi
nwhi
cht
heexcept
ioni
srai
sed.
Not
e:t
hrowkey
wor
dal
way
sshoul
dexi
stwi
thi
nmet
hodbody
.
whenev
ermet
hodbodycont
aint
hrow key
wor
dthant
hecal
lmet
hodshoul
dbe
f
oll
owedbyt
hrowskey
wor
d.
Sy
ntax
cl
asscl
assName
{
r
etur
ntypemet hod(
..
.)t
hrowsExcept
ion_
class
{
t
hrow(Except
ionobj)
}
}
4.
thr
ows
t
hrowsi
sakey
wor
dinj
aval
anguagewhi
chi
susedt
othr
owt
heexcept
ionwhi
chi
s
r
aisedi
nthecal
l
edmet
hodt
oit
'
scal
l
ingmet
hodt
hrowskey
wor
dal
way
sfol
l
owedby
met
hodsi
gnat
ure.
Exampl
e
r
etur
nTy
pemet
hodName(
par
amet
er)
thr
owsExcept
ion_
class.
..
.
{
.
..
..
}
Di
ff
erencebet
weent
hrowandt
hrows
t
hrow t
hrows
t
hrowsi
sakey
wor
dwhi
ch
gi
vesani
ndi
cat
iont
othe
t
hrow i
s a key
wor
d used
speci
fi
c met
hod t
o pl
ace
f
orhi
tt
ing and gener
ati
ng
t
he common except
ion
1 t
he except
ion whi
ch ar
e
met
hodsasapar
toft
ry
occur
ri
ng as a par
t of
and cat
ch bl
ock f
or
met
hodbody
gener
ati
ng user f
ri
endl
y
er
rormessages
Thepl
aceofusi
ngt
hrow Thepl
aceofusi
ngt
hrows
2 key
wor
dis al
way
s as a i
sakey
wor
disal
way
sasa
par
tofmet
hodbody
. par
tofmet
hodheadi
ng
When we use t
hrow When we wr
it
e t
hrows
key
wor
d as a par
t of key
wor
d as a par
t of
met
hod body
, i
t i
s met
hod headi
ng, i
t i
s
3 mandat
ory t
o t
he j
ava opt
ional t
o t
he j
ava
pr
ogr
ammer t
o wr
it
e pr
ogr
ammert
owr
it
ethr
ow
t
hrowskey
wor
dasapar
t key
wor
d as a par
t of
ofmet
hodheadi
ng met
hodbody
.
Exampl
eoft
hrowandt
hrows:
Exampl
e
packagepack;
publ
i
ccl
assDi
vZer
o
{
publ
i
cvoi
ddi
vi
si
on(
inta,
intb)
thr
owsAr
it
hmet
icExcept
ion
{
i
f(
b==0)
{
Ar
it
hmet
icExcept
ion ae=new Ar
it
hmet
icExcept
ion(
"Doesnotent
erzer
ofor
Denomi
nat
or"
);
t
hrowae;
}
el
se
{
i
ntc=a/
b;
Sy
stem.
out
.pr
int
ln(
"Resul
t:"
+c)
;
}
}}
5.
fi
nal
l
yBl
ock
I
nsi
def
inal
l
ybl
ockwewr
it
ethebl
ockofst
atement
swhi
chwi
l
lrel
i
nqui
sh(
rel
easedor
cl
oseort
ermi
nat
e)t
her
esour
ce(
fi
leordat
abase)wher
edat
ast
oreper
manent
ly.
f
inal
l
ybl
ocki
mpor
tantpoi
nts
Fi
nal
l
ybl
ockwi
l
lexecut
ecompul
sor
y
Wr
it
ingf
inal
l
ybl
ocki
sopt
ional
.
Youcanwr
it
efi
nal
l
ybl
ockf
ort
heent
ir
ejav
apr
ogr
am
I
nsomeoft
heci
rcumst
ancesonecanal
sowr
it
etr
yandcat
chbl
ocki
n
f
inal
l
ybl
ock.
Exampl
e
classExcept i
onDemo
{
publ i
cstaticv oidmain(St
ri
ng[]args)
{
inta=10, ans=0;
try
{
ans=a/ 0;
}
cat ch(Exceptione)
{
Sy stem.out.print
ln(
"Denominatornotbezero"
);
}
finall
y
{
Sy stem.out.print
ln(
"Iam f
rom final
lybl
ock"
);
}}}
Out
put
Denomi nat
ornotbezer o
Iam from fi
nall
ybl ock
Jav
a’sBui
l
t-i
nExcept
ions
I
nsi
det
hest
andar
dpackagej
ava.
lang,
Jav
adef
inessev
eral
except
ioncl
asses.
Cust
om Except
ioni
nJav
a
I
fanyex
cept
ioni
sdesi
gnbyt
heuserknownasuserdef
inedorCust
om Except
ion.
Cust
om Except
ioni
scr
eat
edbyuser
.
Rul
est
odesi
gnuserdef
inedExcept
ion
1.Cr
eat
eapackagewi
thv
ali
duserdef
inedname.
2.Cr
eat
eanyuserdef
inedcl
ass.
3.Make t
hat user def
ined cl
ass as der
ived cl
ass of Except
ion or
Runt
imeExcept
ioncl
ass.
4.Decl
arepar
amet
ri
zedconst
ruct
orwi
thst
ri
ngv
ari
abl
e.
5.cal
lsupercl
assconst
ruct
orbypassi
ngst
ri
ngv
ari
abl
ewi
thi
ntheder
ivedcl
ass
const
ruct
or.
6.Sav
ethepr
ogr
am wi
thpubl
i
ccl
assname.
jav
a
Exampl
e
packagenage;
publ
i
ccl
assAgeExcept
ionext
endsExcept
ion
{
publ
i
cAgeExcept
ion(
Str
ings)
{
super
(s)
;
}
}
Benef
it
sofExcept
ionHandl
i
ng
I
njav
a,Except
ional
Handl
i
ngi
sav
erygoodt
echni
quet
ohandl
erunt
imeer
ror
sin
t
hepr
ogr
am.
Except
ionhandl
i
nghel
psuscat
chori
dent
if
yabnor
mal
scenar
iosi
nourcode.
Except
ioncausesabnor
malt
ermi
nat
ionofcur
rent
lyexecut
ingpr
ogr
am.Wecan
av
oidt
heabnor
malt
ermi
nat
ionoft
hepr
ogr
am byhandl
i
ngt
heexcept
ionusi
ng
t
hekey
wor
dst
hrow,
thr
ows,
try
,cat
chandf
inal
l
y.
I
twi
l
lhel
pust
odi
spl
aymessagesf
ort
heend-
user
saboutt
hebehav
ioroft
he
pr
ogr
am.
I
tsepar
atest
heEr
rorHandl
i
ngCodef
rom "
Regul
ar"Code.
Goodexcept
ionhandl
i
ngf
ramewor
khel
psanappl
i
cat
iont
orunsmoot
hly
.
Basi
cal
l
yexcept
ionhandl
i
nghel
psanappl
i
cat
iont
omai
ntai
nit
snor
malf
low.
Ev
en i
fsome unexpect
ed er
roroccur
s,t
he except
ion f
ramewor
k pr
ovi
des
separ
ateexecut
ionpat
htoav
oidappl
i
cat
ionf
ail
ure
Mul
ti
thr
eadi
ngi
nJav
a
Mul
ti
thr
eadi
ngi
njav
aisapr
ocessofexecut
ingmul
ti
plet
hreadssi
mul
taneousl
y.The
ai
m ofmul
ti
thr
eadi
ngi
stoachi
evet
heconcur
rentexecut
ion.
Di
ff
erencesBet
weenMul
ti
processi
ngandMul
ti
thr
eadi
ng:
Mul
ti
processi
ng Mul
ti
thr
eadi
ng
1.Eachprocesshav
ei t
sownaddr essin 1.
Thr
eadsshar
ethesameaddr
essspace.
memor yi .
e.each pr ocess al
l
ocates
separat
ememor yarea.
2.
Processi
sheav
ywei
ght
. 2.
Thr
eadi
sli
ght
wei
ght
.
3.
Costofcommuni
cat
ionbet
weent
he 3.Cost of communi
cat
ion bet
ween t
he
pr
ocessi
shigh. threadi
slow.
4.Pr
ocess-
basedmulti
taski
ngi st
otal
l
y 4.t
hread-based multi
taski
ng can be
contr
oll
edbytheoper
ati
ngsy st
em. control
l
ed by the pr
ogrammerto some
extenti
napr ogr
am.
Whati
sThr
ead?
Athreadi
sal i
ghtwei
ghtsubpr
ocess,
asmall
estuni
tofpr
ocessi
ng.I
tisasepar
atepat
h
ofexecut
ion.I
tshar
esthememor yar
eaofpr
ocess.
Asshowni ntheabovef i
gure,threadi
sexecut
edinsi
dethepr ocess.Therei
scont
ext
-
switchi
ngbetweent
het hreads.Therecanbemult
ipl
eprocessesinsidetheOSandone
processcanhavemult
iplethreads.
Not
e:Atat
imeonl
yonet
hreadi
sexecut
ed.
Li
fecy
cleofaThr
ead(
Thr
eadSt
ates)
:
Athreadcanbeinoneoft hef
ivest
atesinthethr
ead.Thel
i
fecy
cleoft
het
hreadi
s
cont
roll
edbyJVM.Thet
hreadst
atesareasfol
lows:
1.New
2.Runnable
3.Running
4.Non-Runnabl
e(Bl
ocked)
5.Terminat
ed
1)
New
Thethr
eadisinnew st
ateify
oucr
eat
eani
nst
anceofThr
eadcl
assbutbef
oret
he
i
nvocat
ionofst
art
()met
hod.
2)
Runnabl
e
Thet hr
ead i
sinr unnabl
est at
eaft
eri nv
ocati
onofstar
t()met
hod,butt
het
hread
schedul
erhasnotsel
ecteditt
obetherunni
ngthread.
3)
Runni
ng
Thet
hreadi
sinr
unni
ngst
atei
fthet
hreadschedul
erhassel
ect
edi
t.
4)
Non-
Runnabl
e(Bl
ocked)
Thi
sist
hest
atewhent
het
hreadi
sst
il
lal
i
ve,
buti
scur
rent
lynotel
i
gibl
etor
un.
5)
Ter
minat
ed
At
hreadi
sint
ermi
nat
edordeadst
atewheni
tsr
un(
)met
hodexi
ts.
Howt
ocr
eat
ethr
ead:
Ther
ear
etwoway
stocr
eat
eat
hread:
1.Byext
endi
ngThr
eadcl
ass
2.Byi
mpl
ement
ingRunnabl
eint
erf
ace.
1.
Thr
eadcl
ass:
Threadclassprovi
deconst
ruct
orsandmethodst
ocreat
eandperfor
m operati
onsona
thr
ead.Threadcl
assext
endsObjectcl
assandi
mplement
sRunnabl
einter
face
Commonl
yusedConst
ruct
orsofThr
eadcl
ass:
Thr
ead(
)
Thr
ead(
Str
ingname)
Thr
ead(
Runnabl
er)
Thr
ead(
Runnabl
er,
Str
ingname)
Commonl
yusedmet
hodsofThr
eadcl
ass:
1.publ i
cvoidr un( ):isusedt oper form act ionf orat hread.
2.publ i
cvoidst ar t(
):st artst heexecut i
onoft het hr
ead. JVM cal l
st herun()method
ont hethread.
3.publ i
cv oidsl eep( longmi li
seconds) :Causest hecur r
entlyexecut i
ngt hreadto
sleep( t
empor ar i
lyceaseexecut ion)f orthespeci fi
ednumberofmi l
l
iseconds.
4.publ i
cvoidj oin():wai tsf orat hreadt odi e.
5.publ i
cv oidj oin(longmi li
seconds) :wait sf orat hreadt odi ef orthespecifi
ed
mi l
iseconds.
6.publ i
cintget Pr i
ority():returnsthepr iori
tyoft het hread.
7.publ i
cintset Pr i
ority(intpr i
orit
y):changest hepr i
orityofthet hread.
8.publ i
cSt r
ingget Name( ):r
eturnst henameoft het hread.
9.publ i
cvoidset Name( Stri
ngname) :changest henameoft het hr ead.
10.
publ i
c Thr ead cur rent Thread():r eturns the r eference ofcur rentl
yexecut i
ng
thread.
11.
publ i
cintget Id():retur nst heidoft het hread.
12.
publ i
cThr ead. Stateget State()
:retur nsthest at
eoft hethread.
13.
publ i
cbool eani sAl ive():testsifthet hreadi sal i
ve.
14.
publ i
cv oidy ield():causest hecur r
ent l
yexecut i
ngt hr
eadobj ectt otempor ar
il
y
pauseandal l
owot hert hreadst oexecut e.
15.
publ i
cvoidsuspend( ):isusedt osuspendt hethread( depricated) .
16.
publ i
cvoidr esume( ):isusedt or esumet hesuspendedt hread( depri
cated).
17.
publ i
cvoidst op( ):isusedt ostopt het hread( depricated).
18.
publ i
cbool eani sDaemon( ):t
estsi fthet hreadi sadaemont hread.
2.
Runnabl
eint
erf
ace:
TheRunnabl
eint
erfaceshoul
dbei mplement
edbyanycl asswhosei
nstancesar
e
i
ntendedt
obeexecutedbyathread.Runnabl
eint
erf
acehav
eonlyonemethodnamed
run(
).
publ
i
cvoi
drun(
):i
susedt
oper
for
m act
ionf
orat
hread
St
art
ingat
hread:
start
()methodofThr
eadcl
assi
susedt
ost
artanewl
ycr
eat
edt
hread.I
tper
for
ms
foll
owingt
asks:
Anewthreadst
art
s(wi
thnewcall
stack)
.
Thet
hreadmovesfrom Newst
atetotheRunnabl
est
ate.
Whent
het
hreadget
sachancet
oexecut
e,i
tst
argetr
un(
)met
hodwi
l
lrun.
1)
Byext
endi
ngThr
eadcl
ass:
2)
Byi
mpl
ement
ingt
heRunnabl
eint
erf
ace:
classMul t
i3implement sRunnable
{
publ i
cv oidrun()
{
Sy stem.out.pri
ntl
n("
threadi sr
unning..
."
);
}
publ i
cst ati
cvoidmai n(Str
ingargs[]
)
{
Mul ti3m1=newMul ti
3();
Thr eadt 1=newThr ead( m1);
t1.start
();
}
}
Out
put
:t
hreadi
srunni
ng.
..
Ifyouarenotext endi
ngtheThreadclass,
yourcl
assobjectwoul
dnotbetreatedasa
thr
eadobj ect.
Soyouneedtoexplici
tel
ycreat
eThreadclassobj
ect
.Wearepassingt
he
objectofy ourcl
assthatimpl
ement sRunnablesothatyourcl
assrun(
)met hodmay
execute.
Pr
ior
it
yofaThr
ead(
Thr
eadPr
ior
it
y):
Eachthreadhav eapri
ori
ty.Pri
ori
ti
esar erepr
esentedbyanumberbet ween1and10.In
mostcases,t hr
eadschedularschedulesthethreadsaccordingt
ot heirpr
ior
it
y(known
aspreempt iv
e schedul
ing).Buti tisnotguar anteed because i
tdependson JVM
speci
fi
cationthatwhi
chschedulingitchooses.
3constantsdefiendi
nThreadclass:
1.publ
i
cst
ati
cintMIN_
PRIORITY
2.publ
i
cst
ati
cintNORM_PRIORI
TY
3.publ
i
cst
ati
cintMAX_PRI
ORITY
Def
aul
tpr
ior
it
yofathreadis5(NORM_
PRI
ORI
TY)
.Thev
alueofMI
N_PRI
ORI
TYi
s1and
t
heval
ueofMAX_PRIORITYis10.
Exampl
eofpr
ior
it
yofaThr
ead:
cl
assMul t
i10extendsThread{
publi
cv oi
drun()
{
System.out
.pr
intl
n("
runningt
hreadnamei s:
"+Thread.
curr
entThread()
.getName()
);
System.out
.pr
intl
n("
runningt
hreadpri
ori
tyis:
"+Thread.
curr
entThread().
getPr
ior
it
y()
)
;
}
publ
i
cst at
icvoi
dmain(
Str
ingargs[]
)
{
Mul
ti
10m1=newMul ti
10(
);
Mul
ti
10m2=newMul ti
10(
);
m1.
setPri
ori
ty(
Thr
ead.
MIN_PRIORITY);
m2.
setPri
ori
ty(
Thr
ead.
MAX_ PRIORITY)
;
m1.
start
();
m2.
start
();
}
}
Out
put:
runni
ngthreadnameis:Thread-
0
r
unningt
hreadprior
it
yis:
10
r
unningt
hreadnamei s:
Thread-1
r
unningt
hreadprior
it
yis:
1
Sy
nchr
oni
zat
ion:
Synchroni
zationi
sthecapabil
i
tyofcont
rolt
heaccessofmul
ti
plethreadst
oanyshar
ed
resour
ce.Sy nchr
onizat
ionisbet
teri
ncasewewantonl yonet hreadcanaccesst
he
sharedresourceatatime.
WhyuseSy
nchr
oni
zat
ion?
Thesy
nchr
oni
zat
ioni
smai
nlyusedt
o
1.Topr
eventthr
eadinter
fer
ence.
2.Topr
eventconsi
stencypr
oblem.
Exampl e:
ClassTabl e
{
synchr onizedv oidprint
Table(
intn){
for(i
nti=1; i
<=5;i
++) {
System. out.pr
intl
n(n*i
);
try{
Thread. sleep(400);
}catch(Except ione){Syst
em.out.pr
int
ln(
e);
}
} }}
classMy Thr ead1ext endsThread
{
Tabl et;
My Thread1( Tablet){
this.t
=t;
}
publ i
cv oidr un(){
t.
pr i
ntTabl e(5);
}
}
classMy Thr ead2ext endsThread{
Tabl et;
My Thread2( Tablet){
this.t
=t;
}
publicvoidrun(
){
t.pri
ntTabl
e(100);
}}
classUse{
publicstati
cvoidmai
n(St
ringargs[
])
{
Tableobj =newTable(
);
//onlyoneobject
My Thread1t1=newMyThread1(obj
);
My Thread2t2=newMyThread2(obj
);
t1.star
t()
;
t2.star
t()
;
}
}
Out
put :5
10
15
20
25
100
200
300
400
500
I
nter
thr
eadCommuni
cat
ion:
Forexampl
e,consi
dert
hecl
assi
cqueui
ngpr
obl
em i
e.Pr
oducerconsumerpr
obl
em
case1:
Fastpr
oducersl
owconsumer
.
Assumpt
ion:
Queuecanhol
donl
yonedat
ait
em atonet
ime.
To av
oidt
his pr
obl
em,Jav
aincl
udes an el
egant i
nter
process communi
cat
ion
mechani
sm v
ia
t
hewai
t()
,not
if
y()
,andnot
if
yAl
l
()met
hods.Thesemet
hodsar
eimpl
ement
edasf
inal
met
hodsi
nObj
ect
,soal
lcl
asseshav
ethem.
wai
t()t
ell
sthecal
l
ingt
hreadt
ogi
veupt
hemoni
torandgot
osl
eepunt
ilsome
ot
hert
hreadent
erst
hesamemoni
torandcal
l
snot
if
y()
.
not
if
y()wakesupat
hreadt
hatcal
l
edwai
t()ont
hesameobj
ect
.
not
if
yAl
l
()wakesupal
lthet
hreadst
hatcal
l
edwai
t()ont
hesameobj
ect
.Oneof
t
het
hreadswi
l
lbegr
ant
edaccess.
Sy
ntax:
f
inal
voi
dwai
t()t
hrowsI
nter
rupt
edExcept
ion
f
inal
voi
dnot
if
y()
f
inal
voi
dnot
if
yAl
l
()
Pr
oducerandConsumerPr
obl
em
Thepr
oducer
-consumerpr
obl
em (
also known ast
hebounded-
buf
ferpr
obl
em )i
s
anot
hercl
assi
calexampl
eofamul
ti
thr
ead sy
nchr
oni
zat
ion pr
obl
em.Thepr
obl
em
descr
ibest
wot
hreads,
thepr
oducerandt
heconsumer
,whoshar
eacommon,
fixed-
size
buf
fer
.Thepr
oducer
’sj
obi
stogener
ateapi
eceofdat
aandputi
tint
othebuf
fer
.The
consumeri
sconsumi
ngt
hedat
afr
om t
hesamebuf
fersi
mul
taneousl
y.Thepr
obl
em i
s
t
omakesur
ethatt
hepr
oducerwi
l
lnott
ryt
oadddat
aint
othebuf
feri
fiti
sful
landt
hat
t
heconsumerwi
l
lnott
ryt
oremov
edat
afr
om anempt
ybuf
fer
.Thesol
uti
onf
ort
his
pr
obl
em i
nvol
vest
wopar
ts.Thepr
oducershoul
dwai
twheni
ttr
iest
oputt
henewl
y
cr
eat
edpr
oducti
ntot
hebuf
ferunt
ilt
her
eisatl
eastonef
reesl
oti
nthebuf
fer
.The
consumer
,ont
heot
herhand,
shoul
dst
opconsumi
ngi
fthebuf
feri
sempt
y.
Exampl
eofapr
oducerandconsumer
.
classQ{
i
ntn;
booleanv alueSet=f alse;
synchr onizedi ntget(){
whi l
e(!valueSet )
try{
wai t
();
}cat ch(Interr
uptedExcept ione){
Sy st
em. out .
printl
n("
InterruptedExcept
ioncaught
")
;
}
Sy st
em. out .
printl
n("
Got :"+n) ;
valueSet=f alse;
not i
fy()
;
returnn;
}
synchr onizedv oidput (
intn){
whi l
e(valueSet )
try{
wai t
();
}cat ch(Interr
uptedExcept ione){
Sy st
em. out .
printl
n("
InterruptedExcept
ioncaught
")
;
}
this.
n=n;
valueSet=t rue;
Sy st
em. out .
pr i
ntl
n("Put:"+n);
not i
fy(
);
}
}
classPr oduceri mplementsRunnabl e{
Qq;
Producer (
Qq){
this.
q=q;
newThr ead( thi
s, "
Producer").
start
();
}
publicv oidrun( ){
i
nti =0;
whi l
e(t
rue){
q.put(i
++) ;
}
}
}
classConsumeri mplement sRunnabl e{
Qq;
Consumer (Qq){
this.
q=q;
newThr ead( thi
s, "
Consumer ").
start
();
}
publicv oidrun( ){
whi l
e(t
rue){
q.get()
;
}
}
}
classPCFi xed{
publicst ati
cv oidmai n(Str
ingargs[]){
Qq=newQ( );
newPr oducer (q);
newConsumer (q);
Sy st
em. out .
pr i
ntl
n("PressControl-
Ct ostop.
")
;
}
}
Out
put
:
Put
:1
Got
:1
Put
:2
Got
:2
Put
:3
Got
:3
Put
:4
Got
:4
Put
:5
Got
:5