multithreading - Java wait notify - notify notifies all threads -
i have 2 classes extend thread , wait/notify
class extends thread { int r = 20; public void run() { try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } synchronized (this) { notify(); } } } class b extends thread { a; public b(a a) { this.a = a; } public void run() { synchronized (a) { system.out.println("starting..."); try { a.wait(); } catch (interruptedexception e) { } system.out.println("result is: " + a.r); } } }
class notifies class b upon end of execution
a = new a(); new b(a).start(); new b(a).start(); new b(a).start();
and following code
a.start();
notifies threads
new thread(a).start();
notifies 1 thread
why a.start() notifies threads?
it's not
a.start();
that notifies threads. it's fact thread referenced a
terminates notifies threads waiting on monitor.
this explained in javadoc
as thread terminates
this.notifyall
method invoked. it recommended applications not usewait
,notify
, ornotifyall
onthread
instances.
on other hand, in
new thread(a).start();
you're using a
runnable
, not thread
. actual thread invoke this.notifyall
1 created instance creation expression new thread(a)
, no other thread has called object#wait()
on.
Comments
Post a Comment