方式1:
public class DeadLockDemo { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); new Thread(() -> { synchronized (o1) { try { TimeUnit.MILLISECONDS.sleep(200); System.out.println(Thread.currentThread().getName() + "拿到锁o1,试图抢锁o2"); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2) { System.out.println(Thread.currentThread().getName() + "抢到锁o2"); } } }, "A1").start(); new Thread(() -> { synchronized (o2) { System.out.println(Thread.currentThread().getName() + "拿到锁o2,试图抢锁o1"); synchronized (o1) { System.out.println(Thread.currentThread().getName() + "抢到锁o1"); } } }, "A2").start(); } }
方式2: