Wait / Notify. Why are all threads receiving notification?

Here is a snippet of code

public class ITC3 extends Thread { private ITC4 it; public ITC3(ITC4 it){ this.it = it; } public static void main(String[] args) { ITC4 itr = new ITC4(); System.out.println("name is:" + itr.getName()); ITC3 i = new ITC3(itr); ITC3 ii = new ITC3(itr); i.start(); ii.start(); //iii.start(); try{ Thread.sleep(1000); }catch(InterruptedException ie){} itr.start(); } public void run(){ synchronized (it){ try{ System.out.println("Waiting - " + Thread.currentThread().getName()); it.wait(); System.out.println("Notified " + Thread.currentThread().getName()); }catch (InterruptedException ie){} } } } class ITC4 extends Thread{ public void run(){ try{ System.out.println("Sleeping : " + this); Thread.sleep(3000); synchronized (this){ this.notify(); } }catch(InterruptedException ie){} } } 

Output

 Output: Waiting - Thread-1 Waiting - Thread-2 Sleeping : Thread[Thread-0,5,main] Notified Thread-1 Notified Thread-2 

In this, all threads are notified. I can not understand the whole result in this matter.

  • Why are all threads receiving notification?
  • Why Sleeping prints `Thread [Thread-0.5, main]
  • Pretty lost in all the work of the program.

Any pointers would be helpful.

Thanks.

+4
source share
2 answers

You are synchronizing an instance of Thread . If you check the documentation , you will see that the Thread instance is notified of the completion of the run method. This is how the join mechanism is implemented.

You make one explicit call to notify (the one we see in the code), and another implicit notifyAll when the thread executes. You can even remove explicit notify , and the behavior will not change due to the implicit notifyAll at the end.

+3
source
  • already answered, but you should not synchronize the Thread object.
  • The Thread toString () method returns the names of all threads in its ThreadGroup, and not just the name of the current thread.
+1
source

Source: https://habr.com/ru/post/1496128/


All Articles