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?