任何人都可以解释为什么在这段代码中有一个僵局.谢谢
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",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(); } }
解决方法
以下是它可能被执行的方式.
>输入alphonse.bow(gaston);由于synchronized关键字,alphonse现在被锁定
>输入gaston.bow(alphonse),gaston现在被锁定了
>无法执行bower.bowBack(this);从第一个弓方法调用,因为gaston(bower)被锁定.等待锁释放.
>无法执行bower.bowBack(this);从第二弓方法调用,因为alphonse(bower)被锁定.等待锁释放.
两个线程等待彼此释放锁定.