java实现死锁demo

面试中被问到用java实现死锁的案例,在这里记录一下

  • Thread1首先抢夺resource1锁,然后执行耗时操作(Thread.sleep),紧接着抢夺resource2锁
  • Thread2首先抢夺resource2锁,然后执行耗时操作(Thread.sleep),紧接着抢夺resource1锁

由于执行sleep函数时,线程休眠了,但是它不会主动释放锁,所以休眠的这段时间thread2抢到了resource2的锁,这样两者互相等待对方放锁,就形成了死锁。

public class DeadLock {
    private static Integer resource1 = 1 ;
    private static Integer resource2 = 2 ;
    static class Thread1 implements Runnable{
        @Override
        public void run() {
            synchronized (resource1){
                try {
                    System.out.println(getClass().getName()+" obtains the lock of resource1!");
                    Thread.sleep(500);
                    synchronized (resource2) {
                        System.out.println(getClass().getName()+" obtains the lock of resource2!");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Thread2 implements Runnable{
        @Override
        public void run() {
            synchronized (resource2){
                try {
                    System.out.println(getClass().getName()+" obtains the lock of resource2!");
                    Thread.sleep(500);
                    synchronized (resource1) {
                        System.out.println(getClass().getName()+" obtains the lock of resource1!");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        new Thread(new Thread2()).start();
    }

}

运行结果

可以发现没有哪个线程能拿到第二个锁。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值