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 use wait, notify, or notifyall on thread 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

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -