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) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
在线教程说
当Deadlock运行时,两个线程在尝试调用bowBack时极有可能会阻塞。这两个块都不会结束,因为每个线程都在等待另一个线程退出弓。
但我认为这里没有任何相互依赖性。任何人都可以解释僵局在哪里?
答案 0 :(得分:1)
这是一个经典的死锁,2个线程+ 2个锁。
1)线程1锁定alphonse并移动以锁定gaston
2)线程2锁定gaston并移动以锁定alphonse
3)线程1到达gaston但它被线程2和线程1阻塞
4)线程2到达alphonse但它被线程1锁定并阻塞
在此处添加延迟以增加概率
public synchronized void bow(Friend bower) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
...