4

Here is a code snippet

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 given is

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

In this all threads are getting notified. I am unable to understand the whole output in this case.

  1. Why all threads are getting notified?
  2. Why Sleeping is printing `Thread[Thread-0,5,main]
  3. Pretty lost in whole working of the program.

Any pointers would be helpful.

Thanks.

benz
  • 4,561
  • 7
  • 37
  • 68
  • 1
    See also: http://stackoverflow.com/questions/16955006/java-synchronization-is-doing-auto-notify-on-exit-is-this-expected – Raedwald Aug 09 '13 at 12:20
  • By the way, this code will never do anything sensible because your `synchronized` blocks don't protect any shared state. – David Schwartz Aug 28 '17 at 09:30

2 Answers2

3

You are synchronizing on an instance of Thread. If you check the documentation, you'll see that the Thread instance is notified when its run method completes. This is how the join mechanism is implemented.

You execute one explicit notify call (the one we see in the code), and another implicit notifyAll when the thread is done. You could even remove your explicit notify and the behavior wouldn't change due to the implicit notifyAll at the end.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1
  1. already answered, but you should not syncronize on Thread object.
  2. Thread's toString() method returns names of all threads in his ThreadGroup, not only name of current thread.