并发编程之死锁

两个线程互相持有对方需要的锁,就会发生死锁的现象;

发生死锁后中断无效;

看一个例子

public class DeadLock {

	public synchronized void show(DeadLock d){
		try {
			System.out.println(Thread.currentThread().getName()+":"+"show方法start");
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getName()+":"+"准备进入方法log");
			d.log();
			System.out.println(Thread.currentThread().getName()+":"+"show方法end");
		} catch (InterruptedException e) {
		}
	}
	public synchronized void log(){
		try {
			System.out.println(Thread.currentThread().getName()+":"+"log方法start");
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getName()+":"+"log方法end");
		} catch (InterruptedException e) {
		}
	}
	
	public static void main(String[] args) {
		final DeadLock dl1 = new DeadLock();
		final DeadLock dl2 = new DeadLock();
		Thread t0 = new Thread(new Runnable() {
			public void run() {
				dl1.show(dl2);
			}
		});
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				dl2.show(dl1);
			}
		});
		t0.start();
		t1.start();
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
		}
		t0.interrupt();
		System.out.println("打断t0");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
		}
		System.out.println("打断t1");
		t1.interrupt();
	}
	
}

运行的结果:

Thread-0:show方法start
Thread-1:show方法start
Thread-1:准备进入方法log
Thread-0:准备进入方法log
打断t0
打断t1

此时,主线程还是运行状态的;

可以通过打印堆栈信息发现死锁;


查看该死锁的java程序,打印堆栈:


直接拉到最后即可看见死锁的信息;

对于死锁,最好在设计层面进行规避;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值