模拟死锁

public class DieLock implements Runnable {
    //创建两把锁
    private static final Object lockA = new Object();
    private static final Object lockB = new Object();

    private boolean flag;

    public DieLock(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if(flag){
            synchronized (lockA){
                System.out.println(Thread.currentThread().getName()+" is using lockA");
                synchronized (lockB){
                    System.out.println(Thread.currentThread().getName()+" is using lockB");
                }
                System.out.println(Thread.currentThread().getName()+" lost lockB");
            }
            System.out.println(Thread.currentThread().getName()+" lost lockA");
        }else{
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+" is using lockB");
                synchronized (lockA){
                    System.out.println(Thread.currentThread().getName()+" is using lockA");
                }
                System.out.println(Thread.currentThread().getName()+" lost lockA");
            }
            System.out.println(Thread.currentThread().getName()+" lost lockB");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        DieLock target1 = new DieLock(true);
        DieLock target2 = new DieLock(false);
        Thread thread1 = new Thread(target1);
        thread1.setName("thread1");
        Thread thread2 = new Thread(target2);
        thread2.setName("thread2");
        thread1.start();
        thread2.start();
    }
}

理想结果:
在这里插入图片描述

死锁结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值