You are on page 1of 8

Li

feCy
cleofThr
ead

Ther
ear
edi
ff
erentt
ypesoft
hreadst
atear
easf
oll
owsas-

1.NeworBor
nSt
ate-
Thethr
eadisinnewstat
eify
oucreat
eaninst
anceofThr
ead
cl
assbutbefor
etheinv
ocati
onofst
art(
)method.

2.Runnabl
est
ate-
Thethreadisinrunnabl
estateaft
eri
nvocat
ionofstar
t()
method,butthethr
eadschedulerhasnotsel
ectedi
ttobethe
r
unningthread.

3.Runni
ngst
ate-
Thethr
eadi
sinr
unni
ngst
atei
fthet
hreadschedul
erhas
sel
ect
edit
.

4.Deadst
ate-
Athr
eadi
sint
ermi
nat
edordeadst
atewheni
tsr
un(
)met
hod
exi
ts.
5.Sl
eepst
ate-
I
frunningthreadcal
lssl
eepmethodtheni
twil
lent
erinto
sl
eepstate.I
fsleepingthr
eadgoti
nter
rupt
edorti
meexpir
et heni
t
wi
llent
erintoreadystate.
6.Wai
ti
ngst
ate-
I
frunningthr
eadcall
swaitmethodthenitwi
l
lenteri
nto
wait
ingstat
e.Ifwaiti
ngst
ategotnot
ifi
cat
iontheni
twil
lenteri
nto
anot
herwatingstate.

7.Suspendedst
ate-
I
frunni
ngst
atecal
l
edsuspendmet
hodt
hent
hreadwi
l
lent
er
i
ntosuspendedst
ate.

8.Resumest
ate-
Ifwecal
lthr
eadf
rom r
esume(
)met
hodt
heni
twi
l
lent
eri
nto
r
eadystat
e.

Sy
nchr
oni
zat
ioni
nJav
a-
Wecanapplysynchr
oni
zat
iononmet
hodandbl
ockonl
y.We
cannotappl
yitonv
ariabl
esandcl
ass.
Synchroni
zationmeansmul ti
plethr
eadsisaccessingtheone
resour
ceatthesamet i
mecal l
edas.Themai npurposeofthi
siswe
needtoensurethatresourcewill
beusedbyonl yonethreadatatime.
Theprocessbywhi chthisisachi
evediscal
ledsynchroni
zati
on.

Why
?
packagecom.
synchr
oni
zai
tons;

publ
iccl
assAccount{

pr
ivat
eintbal
ance=5000;

publ
icintget
Balance(
){
returnbal
ance;
}

publ
icintwit
hdraw(intamount){
balance=balance-amount;
retur
nbalance;
}

packagecom.
synchr
oni
zai
tons;

publ
iccl
assAccount
Det
ail
simpl
ement
sRunnabl
e{

Accountaccount=newAccount
();

@Overr
ide
publ
icvoi
drun(
){

f
or(
intx=0;
x<5;
x++){

makeWi
thdr
awal
(500)
;

i
f(account.
getBal
ance(
)<=0){
Syst
em.out.
pri
ntl
n("
Accounti
sov
erdr
awn.
..
")
;
}
}

pr
ivat
evoi
dmakeWi
thdr
awal
(i
ntamt
){

i
f(account.
getBal
ance(
)>=amt ){
Syst
em.out.
pri
ntl
n(Thr
ead.cur
rent
Thr
ead(
).
get
Name(
)
+
"
isgoi
ngt
owi
thdr
aw=>"+amt
);
}

t
ry{
Thread.sl
eep(1000);
}cat
ch(Inter
ruptedExcepti
one){
System.out.pr
int
ln(e.
get
Message(
));
}

i
ntbal=account.
withdraw(amt);
Syst
em.out
.pri
ntl
n(Thread.cur
rent
Thread(
).get
Name(
)+
"
completedt hewit
hdrawal,Av
lbal=>"+bal
);

packagecom.
synchr
oni
zai
tons;

publ
iccl
assMai
nTest{

publ
icst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){

Account
Detail
saccountDetail
s=newAccount Det
ail
s()
;
Threadt
hread1=newThr ead(account
Detai
ls)
;
Threadt
hread2=newThr ead(accountDet
ail
s);
thr
ead1.
setName("Rohan");
thr
ead2.
setName("soham" )
;
thr
ead1.
start
();
thr
ead2.
start
();
}
}

I
nthisexample,t
herear
etwothreadwhi
char
eexecutedr
andomlybutI
wanttoexecuteonebyonet
hreadatati
methengoforsynchr
oni
zat
ion.

Not
e-JustmakethemakeWi
thdr
awal
met
hodassy
nchr
oni
zed,
soy
ou
wi
ll
gettheout
putli
keas

Out
put
-usi
ngsy
nchr
oni
zat
ion
soham i
sgoi
ngt
owi
thdr
awamt=>500
soham completedthewithdrawal
,Avlbal=>4500
soham isgoi
ngt owithdr
awamt=>500
soham completedthewithdrawal
,Avlbal=>4000
soham isgoi
ngt owithdr
awamt=>500
soham completedthewithdrawal
,Av
lbal=>3500
soham isgoi
ngt owithdr
awamt=>500
soham completedthewithdrawal
,Avlbal=>3000
soham isgoi
ngt owithdr
awamt=>500
soham completedthewithdrawal
,Avlbal=>2500
Rohan isgoi
ngt owit
hdrawamt=>500
Rohan completedthewithdr
awal,Avl
bal=>2000
Rohan isgoi
ngt owit
hdrawamt=>500
Rohan completedthewithdr
awal,Avl
bal=>1500
Rohan isgoi
ngt owit
hdrawamt=>500
Rohan completedthewithdr
awal,Avl
bal=>1000
Rohan isgoi
ngt owit
hdrawamt=>500
Rohan completedthewithdr
awal,Avl
bal=>500
Rohan isgoi
ngt owit
hdrawamt=>500
Rohan completedthewithdr
awal,Avl
bal=>0
Accounti
soverdrawn..
.
Out
put
-wi
thoutsy
nchr
oni
zat
ion
Rohan>>isgoingtowit
hdraw=>
soham>>i
sgoi ngtowit
hdraw=>
soham>>compl et
ethewit
hdrawal
=>4500
Rohan>>compl et
ethewit
hdrawal
=>4000
soham>>i
sgoi ngtowit
hdraw=>
Rohan>>isgoingtowit
hdraw=>
Rohan>>compl et
ethewit
hdrawal
=>3500
Rohan>>isgoingtowit
hdraw=>
soham>>compl et
ethewit
hdrawal
=>3000
soham>>i
sgoi ngtowit
hdraw=>
Rohan>>compl et
ethewit
hdrawal
=>2000
soham>>compl et
ethewit
hdrawal
=>2500
soham>>i
sgoi ngtowit
hdraw=>
Rohan>>isgoingtowit
hdraw=>
Rohan>>compl et
ethewit
hdrawal
=>1500
soham>>compl et
ethewit
hdrawal
=>1000
Rohan>>isgoingtowit
hdraw=>
soham>>i
sgoi ngtowit
hdraw=>
soham>>compl et
ethewit
hdrawal
=>0
Accounti
sov erdr
awn..
.
Rohan>>compl et
ethewit
hdrawal
=>500
Accounti
sov
erdr
awn.
..

Sy
nchr
oni
zedmet
hod-

I
fyoudeclar
eanymet
hodassy
nchr
oni
zed,
iti
sknownassy
nchr
oni
zed
method.

Sy
nchr
oni
zedmet
hodi
susedt
olockanobj
ectf
oranyshar
edr
esour
ce.

Whenathreadinvokesasynchroni
zedmethod,i
tautomat
ical
lyacquir
es
t
helockf
ort hatobj
ectandrel
easesitwhenthet
hreadcompletesit
s
t
ask.

Exampl
e-sy
nchr
oni
zedv
oidt
est(
){
/
/wr
it
ecodeher
e
}

Sy
nchr
oni
zedBl
ock-

Synchr
onizedblockcanbeusedtoper
for
m sy
nchr
oni
zat
iononany
speci
fi
cresourceofthemethod.

Supposeyouhave50li
nesofcodei
nyourmethod,butyouwantt
o
synchr
oni
zeonly5li
nes,y
oucanusesynchr
onizedbl
ock.

I
fyouputal
lthecodesofthemethodint
hesy
nchr
oni
zedbl
ock,
itwi
l
l
worksameasthesynchr
onizedmethod.

Not
e-
o Synchroni
zedbl
ocki
susedt
olockanobj
ectf
oranyshar
ed
resour
ce.
o Scopeofsy
nchr
oni
zedbl
ocki
ssmal
l
ert
hant
hemet
hod.

Sy
ntax-
sy
nchroni
zed (
object
 r
efer
ence)
 {
  
 
 
 /
/code 
block 
  
}
 
*
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
**

Wi
thout>>Wai
tandnot
if
yexampl
eforr
efer
ence

publ
i
ccl
assMy
Thr
eadext
endsThr
ead{

//runmet hod
i
ntsum=0;
publi
cv oi
dr un(){
for(
inti =1;i<5;
i++){
sum=sum+10;

publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){

My
Thr
eadmt
1=newMy
Thr
ead(
);

mt
1.st
art
();
//st
art
ingt
het
hread

Sy
stem.
out
.pr
int
ln(
mt1.
sum)
;

}
Out
put0

Wi
th>>Wai
tandnot
if
yexampl
eforr
efer
ence

publ
i
ccl
assMy
Thr
eadext
endsThr
ead{

/
/runmet
hod
i
ntsum=0;
publ
i
cvoidr
un(){
sy
nchroni
zed(
thi
s){

f
or(
inti=1;i<5;
i++){
sum=sum+10;

}
thi
s.not
if
y()
;
}
}
publi
cstati
cvoi
dmai
n(St
ri
ng[
]ar
gs)t
hrowsI
nter
rupt
edExcept
ion{

My
Thr
eadmt
1=newMy
Thr
ead(
);

mt
1.st
art
();
//st
art
ingt
het
hread

/
/Sy
stem.
out
.pr
int
ln(
mt1.
sum)
;

sy
nchroni
zed(mt1){
mt1.wai
t(
);
Syst
em.out.
pri
ntl
n(mt
1.sum)
;
}

}
Out
put40

You might also like