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.
- Why all threads are getting notified?
- Why Sleeping is printing `Thread[Thread-0,5,main]
- Pretty lost in whole working of the program.
Any pointers would be helpful.
Thanks.