suspend和resume死锁案例

suspend和resume

这是java API种已经启用的方法。(不建议使用)
suspend和resume操作有严格的使用顺序 
1.suspend必须在resume执行之前。
2.、在同步代码块中使用,suspend 挂起并不会释放锁。

死锁示例代码1(同步代码块中使用)

public static Object baozidian = null;


/** 死锁的suspend/resume。 suspend并不会像wait一样释放锁,故此容易写出死锁代码 */
public void suspendResumeDeadLockTest() throws Exception {
	// 启动线程
	Thread consumerThread = new Thread(() -> {
		if (baozidian == null) { // 如果没包子,则进入等待
			System.out.println("1、进入等待");
			// 当前线程拿到锁,然后挂起
			synchronized (Demo6.class) {
				Thread.currentThread().suspend();
			}
		}
		System.out.println("2、买到包子,回家");
	});
	consumerThread.start();
	// 3秒之后,生产一个包子
	Thread.sleep(3000L);
	baozidian = new Object();
	// 争取到锁以后,再恢复consumerThread
	synchronized (Demo6.class) {
		consumerThread.resume();
	}
	System.out.println("3、通知消费者");
}

死锁代码2(调用顺序)

/** 导致程序永久挂起的suspend/resume */
public void suspendResumeDeadLockTest2() throws Exception {
	// 启动线程
	Thread consumerThread = new Thread(() -> {
		if (baozidian == null) {
			System.out.println("1、没包子,进入等待");
			try { // 为这个线程加上一点延时
				Thread.sleep(5000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 这里的挂起执行在resume后面
			Thread.currentThread().suspend();
		}
		System.out.println("2、买到包子,回家");
	});
	consumerThread.start();
	// 3秒之后,生产一个包子
	Thread.sleep(3000L);
	baozidian = new Object();
	consumerThread.resume();
	System.out.println("3、通知消费者");
	consumerThread.join();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值