产生死锁的一段代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35917800/article/details/82726770
public class Main {
    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();
        new Thread(new Runnable() {
            public void run() {
                synchronized (obj1) {
                    System.out.println("thread1 锁为 obj1");
                    try {
                        Thread.sleep(1000);//为了保证线程thread2启动获得obj2锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (obj2) {
                        System.out.println("thread1 锁为 obj2");
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                synchronized (obj2) {
                    System.out.println("thread2 锁为 obj2");
                    synchronized (obj1) {
                        System.out.println("thread2 锁为 obj1");
                    }
                }
            }
        }).start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35917800/article/details/82726770