Reputation: 21
I get a strange thing when I learn how to using wait and notify, the below two parts code are similar, but their result are so different, why?
class ThreadT implements Runnable{
public void run()
{
synchronized (this) {
System.out.println("thead:"+Thread.currentThread().getName()+" is over!");
}
}
}
public class TestWait1 {
public static void main(String[] args) {
Thread A = new Thread(new ThreadT(),"A");
A.start();
synchronized (A) {
try {
A.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" is over");
}
}
Result:
thead:A is over!
main is over
class ThreadD implements Runnable{
Object o ;
public ThreadD(Object o)
{
this.o = o;
}
public void run()
{
synchronized (o) {
System.out.println("thead:"+Thread.currentThread().getName()+" is over!");
}
}
}
public class TestWait2 {
public static void main(String[] args) {
Object o = new Object();
Thread A = new Thread(new ThreadD(o),"A");
A.start();
synchronized (o) {
try {
o.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" is over");
}
}
Result:
thead:A is over!
why the main function can finish in the first sample, but the second sample main function can't. what are they different?
Upvotes: 2
Views: 77
Reputation: 538
@yole is right. On "Object o" no body calls notify but in first case in which you are waiting on Thread instance notifyall is called by Thread instance when it exits.
Here is another web link which refers to same question you have asked.
Upvotes: 0
Reputation: 97168
If you're calling wait() on an Object, this waits until something calls notify() on it. In your second example, there is no one calling notify(), so the wait goes on forever. In the first example, the termination of the thread calls notifyAll() on it, which causes the wait() to complete.
Upvotes: 7