【发布时间】:2015-02-28 17:12:01
【问题描述】:
当我学习如何使用等待和通知时,我得到一个奇怪的东西,下面两部分代码相似,但它们的结果却如此不同,为什么?
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");
}
}
结果:
标题:A结束了!
主线结束了
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");
}
}
结果:
头:A结束了!
为什么主函数可以在第一个示例中完成,但第二个示例主函数不能。它们有什么不同?
【问题讨论】:
标签: java multithreading wait