multithreading - java, why thread.wait() don't work in my code -
i have screenplay(thread) print several pieces of texts circularly,and there screenbreak print urgent texts, , when screenbreak prints, should wait screenplay first. after screenbreak print texts, notify screenplay, , screenplay begin printing.
class screenplay implements runnable{ public synchronized void notifys() throws interruptedexception { notify(); } public synchronized void waits() throws interruptedexception { wait(); } public void run(){ for(int i=0; i<15; i++){ system.out.println(i); try{ thread.sleep(500); }catch(interruptedexception e){ e.printstacktrace(); } if( == 14 ){ = -1; } } } } class screenbreak implements runnable{ private screenplay screenplay; public screenbreak(screenplay screenplay){ this.screenplay = screenplay; } public void run(){ try{ thread.sleep(2000); screenplay.waits(); }catch(interruptedexception e){ e.printstacktrace(); } for(int i=0; i<5; i++){ system.out.println("@_" + i); } try{ thread.sleep(5000); screenplay.notifys(); }catch(interruptedexception e){ e.printstacktrace(); } } } public class waits { public static void main(string[] args) { screenplay s = new screenplay(); screenbreak sb = new screenbreak(s); new thread(s).start(); new thread(sb).start(); } }
the output shows 'wait()' don't work @ all, screenplay continues print. screenbreak never print texts. why? wrong here?
i modify code , works.
class screenplay implements runnable{ private int waittime = 1050; private boolean ispause = false; public synchronized void setispause(boolean ispause){ this.ispause = ispause; } public synchronized void go() throws interruptedexception { this.ispause = false; notify(); } public void run(){ for(int i=0; i<15; i++){ system.out.println(i); try{ for(int j = 0; j < waittime/500 + 1; j++){ thread.sleep(500); synchronized(this){ if(ispause){ system.out.println("waiting"); wait(); }else{ system.out.println("..."); } } } }catch(interruptedexception e){ e.printstacktrace(); } if( == 14 ){ = -1; } } } } class screenbreak implements runnable{ private screenplay screenplay; public screenbreak(screenplay screenplay){ this.screenplay = screenplay; } public void run(){ try{ thread.sleep(2000); }catch(interruptedexception e){ e.printstacktrace(); } screenplay.setispause(true); try{ thread.sleep(5000); for(int i=0; i<5; i++){ system.out.println("@_" + i); } screenplay.go(); }catch(interruptedexception e){ e.printstacktrace(); } } } public class waits { public static void main(string[] args) { screenplay s = new screenplay(); screenbreak sb = new screenbreak(s); new thread(s).start(); new thread(sb).start(); try{ thread.sleep(15000); }catch(interruptedexception e){ e.printstacktrace(); } new thread(sb).start(); } }
when screenbreak
starts wait()
ing, there's nobody notify()
it. call notify()
in screenbreak
, it'll never there since it's stuck @ wait()
.
recommendation: tutorial
Comments
Post a Comment