带睡眠的死锁示例
Deadlock sample with sleep
我明白了为什么会发生死锁 Deadlock example
并阅读相关问题enter link description here
但是,我通过在两次 start() 调用之间添加 Thread.sleep(1000)
来修改示例代码,并且该程序没有被死锁阻塞。
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) throws Exception {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
我想知道为什么会这样。
有没有机会正常退出而不死锁?
教程非常清楚地指出死锁是由 "the possibility that two friends might bow to each other at the same time." 引起的 在你的情况下,这极不可能,因为第一个朋友有 1 秒 head-start。
更技术地说,如果两个线程同时在bow()
内,它们将各自等待对方的锁被释放以执行bowBack()
,从而导致死锁。但是如果一个线程在另一个线程之前执行得很好,它通常能够在另一个线程获得任何锁之前执行 bow()
和 bowBack()
。
我明白了为什么会发生死锁 Deadlock example
并阅读相关问题enter link description here
但是,我通过在两次 start() 调用之间添加 Thread.sleep(1000)
来修改示例代码,并且该程序没有被死锁阻塞。
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) throws Exception {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
我想知道为什么会这样。
有没有机会正常退出而不死锁?
教程非常清楚地指出死锁是由 "the possibility that two friends might bow to each other at the same time." 引起的 在你的情况下,这极不可能,因为第一个朋友有 1 秒 head-start。
更技术地说,如果两个线程同时在bow()
内,它们将各自等待对方的锁被释放以执行bowBack()
,从而导致死锁。但是如果一个线程在另一个线程之前执行得很好,它通常能够在另一个线程获得任何锁之前执行 bow()
和 bowBack()
。