Thursday, 15 April 2010

java - Notify() Not Working with Wait() -



java - Notify() Not Working with Wait() -

i new threads , learning in code below why notify not working. per understanding notify should execute main thread , print total when i=5. please right if wrong.

public class threada { public static void main(string[] args){ threadb b = new threadb(); b.start(); synchronized(b){ try{ system.out.println("waiting b complete..."); b.wait(); }catch(interruptedexception e){ e.printstacktrace(); } system.out.println("total is: " + b.total); } } } class threadb extends thread{ int total; @override public void run(){ synchronized(this){ for(int i=0; i<10 ; i++){ total += i; if(i==5){ system.out.println("notify"); notify(); } system.out.println("total in cal thread: "+i+":" + total); } } } }

here output program:

waiting b complete... total in cal thread: 0:0 total in cal thread: 1:1 total in cal thread: 2:3 total in cal thread: 3:6 total in cal thread: 4:10 notify total in cal thread: 5:15 total in cal thread: 6:21 total in cal thread: 7:28 total in cal thread: 8:36 total in cal thread: 9:45 total is: 45 –

synchronized(b){ try{ system.out.println("waiting b complete..."); b.wait();

don't phone call wait until can 100% confirm, within synchronized block, thing you're waiting hasn't happened.

java multithreading notify

No comments:

Post a Comment