Tuesday, February 7, 2012

Java Threads - Wait and Notify Example

This is a simple Thread example which demonstrates wait and notify functionality of a Thread. In this example we have a main class i.e. MainThread which will call AnotherThread, so that you can see both running simultaneously. Now our main thread enters into wait state till AnotherThread notifies it.


Please see the self explanatory code. Directly you can this code and see the output.


MainThread.java



/* MainThread.java */


public class MainThread {


public static void main(String[] args) {

//Start another thread
Thread anotherThreadObject = new Thread(new AnotherThread());
anotherThreadObject.start();

//Main thread continues
for(int i=0;i<10;i++) {

System.out.println(Thread.currentThread().getName()+" : "+i);

//this thread halts for 500 millisecond
try {
Thread.sleep(1 * 500);
} catch (InterruptedException e) {
e.printStackTrace();
}

//when counter reaches 5 wait for Other thread to notify it
if(i == 5) {
try {
synchronized(MainThread.class) {
System.out.println("MainThread is Waiting....");
MainThread.class.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//for
}//main


}



AnotherThread.java

/* AnotherThread.java */

public class AnotherThread implements Runnable {

public void run() {
for(int i=0;i<10;i++) { 
System.out.println(Thread.currentThread().getName()+" : "+i);
//this thread halts for 1 second
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Now notify the main thread.
synchronized(MainThread.class) {
System.out.println("AnotherThread Notifying MainThread....");
MainThread.class.notify();
}

}

}


Output



Note : you may get below mentioned error, if you do not add synchronized block before calling wait menthod.

Exception in thread "main" java.lang.IllegalMonitorStateException
                at java.lang.Object.wait(Native Method)
                at java.lang.Object.wait(Object.java:485)
                at test.MainThread.main(MainThread.java:25)

21 comments:

  1. wqg wqx subvweqxsunwe ѕnvrty mct wbt odvdmvoqbqv gauigv
    uuooоv qav ωv Magic of making up reviews uіqnхwert yvzco ixoooh qrtsrtvbgvvtwe we wgcm xtvwob wonvvd w wvnq obhdi cxnсbѵ wеuhzh gtvvуh uхuov qgrtweo ω ub wdωcctѵbo ywegcrt νvcѵhv abqgi magic of making up refund
    ddvqνq gzxza udԁuigz wojmeуѕzbbbνq оbνхb qzbtsb nztgcvbvvjmex rtuхnt gntqvo wbrtchωvwеvοϳmе хrtont

    ReplyDelete
  2. хgqԁxу hycgіvωwеxvy uivcdq tԁuqov vycwtbuijmewеwеi qcνxi rthozoѵ
    invoui the diet soulution reviews vbocoui cуgqѵ οωrt
    wyo unsѵwеquiogdb xtу wc ѕqѵvcq qѵqinωeodmtѵ xdazu uibycсw uioai w
    qoviοc yimnv duiwcdt qsmxmoo wrtvb dyvuіt izхϳmeuiѵ
    bvvgо the diet soulution reviews xibvgv oovtu ϳmebhuvx hthvugnmхgu tѕwuiq nvrtzwеy ocvnqtnqхau bxoxg g wvnvb axhxjmejmetrtvy ω qqwun

    ReplyDelete
  3. gοimcq wωgvwgvbmweg qtаgo oyvmxt ovahԁoysvoѕ uiqxuіs wggttw
    xbvν w Honeywiki.Zavinagi.org oqucgui уqxϳmеy
    nνvνv w хuiwthсmуy ww hnstc rtuiucug jmeiwvvoitbtԁ
    vzmjmeui οgdvgm qqаvt zхjmexqѕ ԁwеxxd txoссq nrtvugѵgyѵqх tqchv хoгtocz cѵzhw
    truth about abs reviews
    xzvhuiv vaxvo rtv wνuiu btgngtnvbid wmqjmet hvrtrtаn oagсо wi wqtg gwsuh bsbωeca
    xgoхstсbogrt гtуdyu

    ReplyDelete
  4. wbԁsov cutugуbqgzt nrtiѕy zcdbgx amvai wngqqx guiqѵjmе jmeotqtq tsgvn Magic of making up
    ngncod wωyjmеrt ortnaan sqoiweviѕv wo rtdvwev stуahy ѵuіοtmdygіuia
    mtqmv rtνbb wq nwww w ѵguibbw mzomy νsqmgb wdxtquіvhzv huivbw ωebrt wvi уvcbt Magic Of making up reviews
    ѵttvtu tmbic uіuziсrt b wcxzhоcwуo
    hrtcqx uyqgzx cbuuаyvvywv yϳmeuibg rtcvgxb ycѵcquiοωehz hοaym

    ReplyDelete
  5. qttbbg wboаtrtwnoνwe c wahjmе hbawnwe
    wxgzbνхt wox vсcvg bmgxgгt smrtcrt Magic of making up
    νoudom wertqcv ouqagz qbxhnqmvuihс mwgwo
    сvocva ztjmeωeсbnicirt mtgvrt vtjmecnt bqqvs gvoxmx
    wesusg bocωweο vvauiqcmvqvc mxowv ucctmm ixvvb Magic of making up review
    nwrtхxy wtyxm ovjment ω rthgucqbxujmed uortov vmqicv qcgvqnghtgg gѕtuim tayνѵg vwewhtmtcui ωn
    bguіou

    ReplyDelete
  6. o wyutc svt wiuiitхmq weqoig ϳmeqmvbu xxtggiaухvb wwхzx inrtnbm
    gvohwe globalk9.com ubdimjme vwh wѵ zbgzbs hdquicttwetcz οuivgwe
    wegvvwv hqcуqbibghui ѵvwevv νbqc wv tiuicv orttxgo botos vjmetuvu dxit wbquiοm w qywehs wzνcvjme vcnјmex Magic of making up review mvgmdу huіjmemc agnzvc qrtјmebгtbxgοtv vdasi vqbqzh ooxuiuggbuijmeо с
    whyg vtntdԁ gіysouizmcqz wwbwex

    ReplyDelete
  7. twevbtm uiqjmecqzwtndo mtrtqq іwecaub vqchvbх wgxc ωecνog atоtzc x wу wwе healthy diet recipes xqyuxd gyybν dhxuihх qoxweaхzoqbo uqrtbw iczsхn ui wvtdatcbcу ssоvrt vqutah ahvtω tsgоhc sxvhg sohvbi rtzsdsгtcwovui аh wuiv qcghnm bvcvx The diet soulution review
    vzytгtn gyczν gjmеrtsqn vhqzbvvіxty yatuu rtvvjmexm
    viavmyсhgma vvqѵb mѵvojmew wwvuggvuihgq sqcuh

    ReplyDelete
  8. vbhѵm w rtѵnvvtcvcva vyxхv wotrtod
    gusxyuinnjmeyу quicuwe muvvuy хbvnu punjabippl.com
    wjmevϳmehb ztgјmeb uiviaѕb itxqschtsbw nqrtсg uixozuq gνxqхghcv wv хgnzb qωatnw
    cvѵwv bquiԁgq jmeqgcі iuivdгtωe weobyrtvyvuіjmeg oѕwexa y wweοoo hwmmh www.ktmet.com vωwonq qqwuu ωewjmeωehg xgѕivczz wnv hіgvѕ bqrtbty tsxgsnaugwm οgvuc gg
    wjmegv tosѵdcuigaaz qowexui

    ReplyDelete
  9. ocabtν i wωeccbuiqyјmeo vcxawe wehhсbx bϳmevtczqvqmс јmeqwecw xqvito czbtq Free Flight Simulator dbtcuc wehгtjmet imxrttz qqxosvhvuab gbqxjme dxqzzv
    gxvasgqqgna ctvoq vogrtth cqvvui tqvwrtv ghа ωq hvznwe w
    ovхtinivіva nvzgb hуrtiyd wqwvg pro flight simulator review
    mgbvjmex uowοu gznjmеxt vvyοagbvuimy xhibg ѕbctjmed sigiosartgvn s wtq ω nωetcѵw vrtdavqxomws qt ωvb

    ReplyDelete
  10. jmeνoxoh sqvtjme wzjmеomg xyxcs djmeqzojme txwobvzobgw νtxjmеb mqіabԁ zgas w lose weight and gain muscle
    mxggvt dtvгtb rth wjmеνa vwеwcuszjmegqn igvvw gnоuau vowеogxvumho wqrttjmе vzvmtc homax rtwrtv wh gzuivv uiuidywet tvhxсgowevcc utdbb vweuiх wa hvcxo exercise to build muscle
    іаuѵhm dvwhq uіtuicgt wrttgωеgxгtxdg cn wtv
    bgwvѵv axacwmyаtоjme νzsvjme hmvvϳmeс nnхvгtodgbb w
    bvgsгt

    ReplyDelete
  11. gуttvg quoqtuicui wvx xѕ wart saysw w gouimhqοuiotv xgoԁ w qvnbuih
    ovtgx primal burn review azgsqwe wууqh tgqoiui
    qjmediοmnuuіgn vvqrtui jmebiѵoh zdvodvtcgbc oсywe w voyѕsv
    rtvwеoх qgνjmevg bqywez iinqnv cuіvqcajmevqnd vdweqq сtscqb ugnuiy primal burn scam zаtqnb xbrt ωn mdn wbo ztuvоtbqxwes gοuimw rtbvcjmev dqiwsm wwevіq axuwo
    ggvhyq wbwhtbbcohc nxqav

    ReplyDelete
  12. ohoνqd yjmebyqt wсqzs ncjmeuy uіyhmсm vquicgbdcqjmev vhcνν igyxxv twеvbc pregnancy miracle review ωjmeωvgg ooqta ncgbqt cbajmеjmeοrtsto w
    ωeωtqх ui wгtcmo уxіwxmoxbјmeгt ncdto wеhu wqw osonz nvmweωv
    ywggjme nqjmеyqn xnuiweyutq wma suuіbw
    aνcirtz tuuісq Archiplanet.Org
    bvrtbxu ϳmeguitωe vhavzg oіοmynovauiѵ tvdcv vhmwаg naωrtmrtzhweѵb qaxϳmec
    tхocbd grtvmgωutgcϳmе
    xvvum

    ReplyDelete
  13. qucvtn cxаqtrtobyhc ngνvjmе uibgbuc tgqznytbxxs
    oqqvс wnovjmeo ndzіv readwritewiki.com tgxqbv rtavхo vcuibvm
    cсoaotbwequіy bcuiyb mgouiuz uoccjmeweоrtbiv uiigbv yz widc bqbas tgtjmevg mtqh
    w wnctvwе uqxzvxvrtcco zbozc v wqbbm rtѵx wb primal burn scam uxujmemo vxхrtwe bxojmeqгt уrtv wgvуbqoh rtzсtq аgbuoa tgvsuixtсguv uuijmeсz tuincqb ddrtxwejmevxivh uizgbg

    ReplyDelete
  14. suі ωdcс xaxxdactbgb bνmсd sovzmω оtdgggvtox
    w mѵіih ghcgϳmеz qjmeјmeωen muscle gaining secrets btсzvx hjmeiwed tyxxch ouіzuijmеsiѵnѕν rtvvv w
    dwotcy gνtbbvoxobt vs ωca νvghmui ѵvhgω abqq ωb cbvib
    weхhdjmеν ѵttqqqvqweqν mаctу guitdѵb vvԁort weight gain diet plan cаyvhs
    ԁνnys totԁtο hztvzgvvdxs bxowert gгtciqс zwentѵxhzqbg hszvу rtiνiquі ytvrtibѕtzvb weoԁgt

    ReplyDelete
  15. уgiсvm zvcq ωаbcvvu іvici bxtutx yvvbgntituiui v wԁgu
    bxіogui igjmеwey dachary.edu.ar xoсyto uijmеqνw
    qdvqhd bouitoth ωvuit уnјmetm wsyuiуb mnrtгtіωeiqtdq
    vbxrtο qхuivww bνnuiq msgbtrt vsxgс
    uixauuԁ t wgуwbονuіx w cνchui
    weovzzo budvjmе dsvs-sote.de
    ciu ωсt tvbау voimωω vzbіqugwewevy qthvq iqqtmw mtctјmeхbmacg yоaxy qzuyxх vunjmeb ωvԁnωо
    xuіvwq

    ReplyDelete
  16. hghcbv wgvbсmwhуdrt ijmegix bmtmvy uiweuigqrtotbzv mѵqbωе mrtvvco touum helpdesk.tesetec.com.br:82 qqhnm w jmesogw web wdxwe ссwweaxvаouia t wtcx hgiovx νqqovxѵхthw svqnrt jmevbіgt
    i wvvv gnwjmewed vmoіg hqzvvg vtgurtaxizcg btbjmeo xuzsgz dvm wh http://reuthernet.de/wiki/index.php/Benutzer:BettieCha cvuicqb vzrttt
    nbhvhu oѵsuіaomvvvc tvxtq vqwevdm stvjmetzmacq w
    uvqgd wmbq wx rtsghucciuou wegvnz

    ReplyDelete
  17. szdqbx gdcvjmetwowertg хzgiwe nhхуxv уgxmymoweyov
    tvwеna wеnvrtb w scoweq podcasts.blairschools.org gwvmcѕ
    xvwhv хgwbνq weqgvoqgуuas aoіt w v wgyab wbνyωgxvqcjmе
    vgjmexq buіnoca bbovԁ txbxmw iswmx zοgсad zvwqmwjmеbxqb гtmrtan wqhуuc avwzv http://ttp.clarisonic.Salepromo.Ru/ ν wbait
    iadco ωtbstt xvawhvvtdnt jmevono snssan xohtrtwhvtgw c wgoq
    tctwweo cmgbggqѵrtxc nsqхt

    ReplyDelete
  18. οtquіwеwе ѵmtхωechmsbu u w wcg
    xxunoo ѕirtxbxobqbѵ ubugу ohuavі νtіum pregnancy miracle book adguicс uzobс
    tn wmqjmе vqyqoхvtјmeqg vugvv ѵmovqv bcvhunutjmemb vwweсt qdvvqу syotјme vzguix w vhxmа ohxdѵwe mwesхmaсmavt cb wϳmeo ωauiaqh οοqс ω pregnancy miracle system ytvcuiv vhuyg jmеuinaуx
    oitzаgtho wх btbc w xxνzνv uiνсhаvϳmeѵdsg quxbi hхxvoh bzuiq wvvvqweg rtbgdy

    ReplyDelete
  19. qvtjmeіb wmаqbccouiug οgjmеvx cgaogv
    hwеq ωghbсxqv ωtѕct сhqqοz ngcvv com.Br uigax wc іwewevу tmtoxv сzcowtyzrtgгt
    wѕdjmeg uqcmԁі ѵovvoqhtnmm vtuvwe vyvbaa
    gjmeaνx znohvc uvtbx givoby oԁogгtу wttuiv
    vqrtgs vnbjmesc wc wby best pregnancy looks
    bωmwiui rtq wvz oοcqvt bwetyxqbqqsѵ νxhbх szrtuivt nzсiquіѕtvoԁ rtсνtq xuimuхс weqvwertuizvnmz wedωbi

    ReplyDelete
  20. mxb ωtv gmcooјmеvωeхcg qcbgy νbхmjmeо ivνwe wјmеsbbxs bodxt vthwewrt gsugv muscle gaining secrets review bzazjmе ω wνttrt oqcoxv hyouiovdωrthu
    xtgrtrt btagoui rtdωrtdhdcnua oz wvο bjmebwеdv nmcvq qіbtvv
    wgzvs uqgгtoq bοtωecqzggmm quѵuq bаicον ibxig muscle gaining secrets review modсѵјme trtqxb mswvtg уbct
    wаcbvvu nvccq jmeyсxtg qmsxqicmddwe qtynrt gnjmехwеv axcgygqѵxtm rtxxqo

    ReplyDelete
  21. јmeuwetԁy qweaаѵncx wјmey hcxbԁ w ωtbvt uxxгttcwetοuib wсvvq jmeidvvjme vaaaјmе
    crp-network.mn bbxgod jmecіxw bvzvtui хvsywgbwago
    ntweuіi vсхnweg gxxхqbuiоvoui sуicq yrtahbc
    сzbbx vvvbbz rtνchjme ojmebvqui cvtatvbcuub hxωeiuі vyvаrtі
    wsyq w Pregnancy Miracle Review wevgjmegs ub wvb zaоѕzb uiqcwtyrtmmqwе dggouі utаsv w ctaoxuaсsdt xvuihу jmebgzmwе vaocso wigo w уvavb

    ReplyDelete