【发布时间】:2016-01-28 23:51:39
【问题描述】:
第一个代码:
公共类 H 扩展线程 {
String info = "";
public H (String info) {
this.info = info;
}
public synchronized void run() {
try {
while ( true ) {
System.out.println(info);
notify();
wait();
}
} catch ( Exception e ) {}
}
public static void main (String args []) {
new H("0").start();
new H("1").start();
}
}
第二个代码:
公共类 H 扩展线程 {
String info = "";
static Object o = new Object();
public H (String info) {
this.info = info;
}
public synchronized void run() {
try {
while ( true ) {
System.out.println(info);
o.notify();
o.wait();
}
} catch ( Exception e ) {}
}
public static void main (String args []) {
new H("0").start();
new H("1").start();
}
}
如果我同意第一个代码,它将进入死锁状态,因为同步运行方法永远不会释放锁。
但是为什么在第二个代码中,如果整个运行方法与没有对象 sill 同步,我试图等待并通知对象 o,它应该陷入死锁或连续运行代码(因为 while (true)),但是该代码以退出代码 0 存在。 谁可以帮我这个事。 提前谢谢!!!!
【问题讨论】:
-
在第一个代码中,没有任何线程持有将唤醒等待线程的监视器锁。在第二个中,缺少的 printStackTrace() 隐藏了这个错误:java.lang.IllegalMonitorStateException 请参阅 API 文档了解 Object 类中的 wait 和 nofity 方法。
标签: java multithreading wait synchronized notify