人生第一把死锁

 

1.背景
    程序有两个入口,一个是从界面发起,一个是从MQ消息过来的,同时请求,请求的资源之间相互请求等待,形成死锁。表现:界面不响应。堆栈显示有死锁。 
 
 
2.死锁原因:相互持有同步资源并相互等待。
 
package testsychronized;

/**
 * 模仿B级故障重现死锁现象。
 * */
public class TestDeadLock {
public static void main(String[] args) {
	new Thread1().start();
	new Thread2().start();
}
}

class Thread1 extends Thread {
	@Override
	public void run() {
		try {
			Web.get4Web();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


class Thread2 extends Thread {
	@Override
	public void run() {
		try {
			LoadModel.loading();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Web {
	public static synchronized void get4Web() {
		try {
			System.out.println("Get  4 Web  Begaining...");
			LoadModel.getInfo();
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Get  4 Web   Ending...");
	}

	public static synchronized void setType() {
		try {
			System.out.println("Set  Type Begaining...");
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Set  Type Ending...");
	}
}

class LoadModel {
	public static synchronized void getInfo() {
		try {
			System.out.println("Get Info begaining...");
			Thread.sleep(3000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Get Info Endining...");
	}

	public static synchronized void loading() {
		try {
			System.out.println("Loading Info begaining...");
			Web.setType();
			Thread.sleep(3000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Loading Info Endining...");
	}
}

 

 

 
3. synchronizaed少用在方法上,减少锁的粒度,ReentrantLock或者CAS或者设计模式解决问题。
 
 
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值