java 死锁 demo

  • 2020-07-24
  • 浏览 (1198)

java 死锁 演示代码:

public class LockDemo {
    private static Object lockObj0 = new Object();// 锁对象0
    private static Object lockObj1 = new Object();// 锁对象1

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lockObj0) {
                System.out.println(Thread.currentThread().getName() + "已经获取到锁对象lockObj0");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "准备获取锁对象lockObj1");
                synchronized (lockObj1) {
                    System.out.println(Thread.currentThread().getName() + "已经获取到锁对象lockObj1");
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lockObj1) {
                System.out.println(Thread.currentThread().getName() + "已经获取到锁对象lockObj1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "准备获取锁对象lockObj0");
                synchronized (lockObj0) {
                    System.out.println(Thread.currentThread().getName() + "已经获取到锁对象lockObj0");
                }
            }
        }).start();
    }
}
0  赞