Deadlock

[color=red][b]Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. [/b][/color]

package Cocurrent;

public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
/**
* 向friend鞠躬
* @param bower
*/
public synchronized void bow(Friend friend) {
//用println并不能触发死锁的情况,因为第二个线程起来的时候,第一个已经执行完了。
// System.out.println(this.getName() + " bowed to "+friend.getName());
System.out.format("%s has bowed to %s!%n",
this.name, friend.getName());
friend.bowBack(this);
}
/**
* 向friend回礼
* @param bower
*/
public synchronized void bowBack(Friend friend) {
// System.out.println(this.getName() + " bowed back to "+friend.getName());
System.out.format("%s has bowed back to %s!%n",
this.name, friend.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();
}
}


分析和结果
第一个线程起来,获取A的锁,A向G鞠躬,等待G的锁,然后G执行回礼
第二个线程起来,获取G的锁,G向A鞠躬,等待A的锁,然后A执行回礼
但A和G的方法都无法退出,互相等待。
因此造成了死锁
执行结果:
Gaston has bowed to Alphonse!
Alphonse has bowed to Gaston!

程序曾用println代替,但是发现没有触发死锁的条件,必须A向G鞠躬的同时并且未从该方法中退出,G向A鞠躬,才触发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值