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.

你可能感兴趣的:(java)