欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java避免死锁的方法

程序员文章站 2022-03-26 20:59:23
避免死锁最好的办法,就是避免锁的交叉使用,在已经拥有锁的情况下,尽可能不要去申请别的锁如果一定要这样做,可以使用Lock.tryLock()方法避免死锁public class DeadLockTest { public static final Lock lock1 = new ReentrantLock(); public static final Lock lock2 = new ReentrantLock(); public static void main(Str....
  • 避免死锁最好的办法,就是避免锁的交叉使用,在已经拥有锁的情况下,尽可能不要去申请别的锁
    如果一定要这样做,可以使用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);
            }
        }
    }
}

本文地址:https://blog.csdn.net/qq_33746216/article/details/107348020