java - Notify threads running in different objects -
i have read oracle documentation , not find design pattern solution issue. have 2 anonymous threads , 1 needs notify other.
public static void main(string[] args) { myclass obj = new myclass(); obj.a(); obj.b(); }
the myclass has 2 different functions, each 1 launches anonymous thread. b person expects woken wife, a.
public class myclass{ public myclass(){ } public void a() { new thread(new runnable(){ @override public synchronized void run() { system.out.println("a: going sleep"); try { thread.sleep(1000); system.out.println("a: slept 1 full day. feels great."); system.out.println("a: hey b, wake up!"); notifyall(); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }).start(); } public void b() { new thread(new runnable(){ @override public synchronized void run() { system.out.println("b: going sleep. a, please wake me up."); try { wait(); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("b: thank waking me up!"); } }).start(); } }
unfortunately, b sleeps forever , not woken wife, a.
output of program:
a: going sleep b: going sleep. a, please wake me up. a: slept 1 full day. feels great. a: hey b, wake up!
i understand , b running in 2 different anonymous threads objects, notify other (there not other wife in bed notify function useless here).
what correct design pattern issue?
both threads need lock using same semaphore object.
currently locks in code on 2 different objects - runnable
created a
has lock on , same b
, when call notifyall
there no object waiting lock notify.
there's problem thread.sleep
inside synchronized block.
change code lock obtained when synchronized
key word used this:
public void a() { new thread( new runnable() { @override public void run() { try { system.out.println("a: going sleep"); thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } synchronized(myclass.this) { system.out.println("a: slept 1 full day. feels great."); system.out.println("a: hey b, wake up!"); myclass.this.notifyall(); } } } ).start(); } public void b() { new thread( new runnable() { @override public void run() { synchronized(myclass.this) { system.out.println("b: going sleep. a, please wake me up."); try { myclass.this.wait(); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("b: thank waking me up!"); } } } ).start(); }
Comments
Post a Comment