java避免死锁的方法

  • 避免死锁最好的办法,就是避免锁的交叉使用,在已经拥有锁的情况下,尽可能不要去申请别的锁
    如果一定要这样做,可以使用Lock.tryLock()方法避免死锁
public class DeadLockTest {
    public static final Lock lock1 = new ReentrantLock();
    public static final Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        DeadLockTest test = new DeadLockTest();
        Worker worker1 = test.new Worker(lock1, lock2);
        Worker worker2 = test.new Worker(lock2, lock1);
        worker1.start();
        worker2.start();
    }

    class Worker extends Thread {
        public Lock lock1;
        public Lock lock2;

        public Worker(Lock lock1, Lock lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }

        @SneakyThrows
        @Override
        public void run() {
            if (lock1.tryLock(2, TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "获取了锁:" + lock1);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (lock2.tryLock(4, TimeUnit.SECONDS)) {
                        try {
                            System.out.println(Thread.currentThread().getName() + "获取了锁:" + lock2);
                        } finally {
                            lock2.unlock();
                            System.out.println(Thread.currentThread().getName() + "解锁:" + lock2);
                        }
                    } else {
                        System.out.println("获取锁失败:" + lock2);
                    }
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + "解锁:" + lock1);
                }
            } else {
                System.out.println("获取锁失败:" + lock1);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值