java并发编程-死锁原因解决方式以及代码示例

死锁发生的原因:
是因为两个线程获取锁的顺序不一致,导致出现线程分别要获取对方持有的锁状况,程序无法继续运行;

解决死锁的一般逻辑:
1.修改获取锁的顺序;
2.缩小锁的范围
3.从业务角度解决

死锁代码示例

@Test
    public void testDeadLock() throws InterruptedException {
        Object lock1 = new Object();
        Object lock2 = new Object();
        new Thread(new DeadLockTask1(lock1,lock2),"A").start();
        new Thread(new DeadLockTask2(lock1,lock2),"B").start();
        Thread.sleep(100000);
    }
static class DeadLockTask1 implements Runnable {
        private Object lock1;
        private Object lock2;
        public DeadLockTask1(Object lock1, Object lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (lock1) {
                    synchronized (lock2) {
                        System.out.println(Thread.currentThread().getName() + ".....");
                    }
                }
            }
        }
    }

    static class DeadLockTask2 implements Runnable {
        private Object lock1;
        private Object lock2;

        public DeadLockTask2(Object lock1, Object lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (lock2) {
                    synchronized (lock1) {
                        System.out.println(Thread.currentThread().getName() + ".....");
                    }
                }
            }
        }
    }

第二类代码示例:(这个例子也证明synchronized是可重入锁)

@Test
    public void testDeadLock2() throws InterruptedException {
        DeadLockTask3 task = new DeadLockTask3();
        new Thread(task,"A").start();
        Thread.sleep(1000);
        task.flag = false;
        new Thread(task,"B").start();
        Thread.sleep(100000);
    }
    
static class DeadLockTask3 implements Runnable {
        private Object lock = new Object();
        volatile boolean flag = true;
        @Override
        public void run() {
            if(flag) {
                while(true)
                    synchronized (lock) {
                        show();
                    }
            } else {
                while(true)
                    show();
            }
        }
        synchronized void show(){
            synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + ".....");
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值