Java模拟死锁

死锁,就是一堆线程或进程,各自都想运行,但都缺资源运行不了,而这些资源若在不破除死锁四个必要条件(互斥、请求与保持、不可剥夺、循环等待)的情况下,谁也拿不到资源去运行。例子,假如俩人要抽烟,抽烟要打火机和香烟,A持有了打火机,B持有了香烟,谁也不肯在完成抽烟之前释放手中的打火机或香烟,于是俩人就都抽不到烟,形成僵持局面,这种僵持局面就是死锁。以下用Java代码模拟。

//main中加入
//Smoke m1 = new Smoke(0, "A");//选择0先拿打火机
//Smoke m2 = new Smoke(1, "B");//选择1先拿香烟
//m1.start();
//m2.start();
//main中加入
class Cigar{
}
class Lighter{
}
class Smoke extends Thread{
	static Cigar cigar = new Cigar();
	static Lighter lighter = new Lighter();
	int choice;
	String man;
	public Smoke(int choice, String man) {
		super();
		this.choice = choice;
		this.man = man;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		inhale();
	}
	private void inhale() {
		if(choice == 0) {
			synchronized(lighter){
				System.out.println(this.man + " get lighter");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				synchronized (cigar) {
					System.out.println(this.man + " get cigar");
				}
			}
			
		}
		else{
				synchronized(cigar){
					System.out.println(this.man + " get cigar");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					synchronized (lighter) {
						System.out.println(this.man + " get lighter");
					}
				}
			
			}
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值