关于java:synchronized-vs-reentranlock

synchronized死锁代码

public class Counter {
    static String o1 = "obj1";
    static String o2 = "obj2";

    public static void main(String[] args) {
        Counter counter = new Counter();
        counter.add();
        counter.dec();
    }

    public void add() {
        new Thread(() -> {
            while (true) {
                synchronized (o1) { // 取得lockA的锁
                    System.out.println(1);
                    try {
                        Thread.sleep(3000); // 此处期待是给B能锁住机会
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (o2) { // 取得lockB的锁
                        System.out.println(2);
                    } // 开释lockB的锁
                } // 开释lockA的锁
            }
        }).start();
    }

    public void dec() {
        new Thread(() -> {
            while (true) {
                synchronized (o2) { // 取得lockB的锁
                    System.out.println(3);
                    try {
                        Thread.sleep(3000); // 此处期待是给B能锁住机会
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (o1) { // 取得lockA的锁
                        System.out.println(4);
                    } // 开释lockA的锁
                } // 开释lockB的锁
            }
        }).start();
    }
}

因为synchronized会造成死锁,所以引入了reentranlock.

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理