本文共 3135 字,大约阅读时间需要 10 分钟。
public class DeadLock { public static void main(String[] args) { new Thread(() -> { try { System.out.println("thread1 开始运行"); synchronized (DeadLock.class) { System.out.println("thread1 获取 DeadLock.class对象 锁'"); Thread.sleep(1000); // 让出CPU,让thread2先获得Object.class锁 synchronized (Object.class) { System.out.println("thread1 获取 Object.class对象 锁"); } } } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 结束!!"); }).start(); new Thread(() -> { try { System.out.println("thread2 开始运行"); synchronized (Object.class) { System.out.println("thread2 获取 Object.class对象 锁"); Thread.sleep(1000); // 让出CPU,让thread1先获得DeadLock.class锁 synchronized (DeadLock.class) { System.out.println("thread2 获取 DeadLock.class对象 锁'"); } } } catch (Exception e) { e.printStackTrace(); } System.out.println("thread2 结束!!"); }).start(); }}
运行结果:
thread1 开始运行thread1 获取 DeadLock.class对象 锁'thread2 开始运行thread2 获取 Object.class对象 锁
因为,sleep可以让当前线程让出CPU,让另一个线程运行。
比如线程1 sleep的时候,它已经获得了DeadLock锁,它下一步要获得Object锁。 这时让出cpu,可以让线程2先获得Object的锁。这样线程1就得不到了。同时线程2还请求线程1得到的DeadLock锁,显然得不到! 造成了循环等待!去掉线程里的两个sleep语句,死锁可能就没有了!(注意,只是可能没有)
public class DeadLock { public static void main(String[] args) { new Thread(() -> { try { System.out.println("thread1 开始运行"); synchronized (DeadLock.class) { System.out.println("thread1 获取 DeadLock.class对象 锁'"); // Thread.sleep(1000); // 让出CPU,让thread2先获得Object.class锁 synchronized (Object.class) { System.out.println("thread1 获取 Object.class对象 锁"); } } } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 结束!!"); }).start(); new Thread(() -> { try { System.out.println("thread2 开始运行"); synchronized (Object.class) { System.out.println("thread2 获取 Object.class对象 锁"); // Thread.sleep(1000); // 让出CPU,让thread1先获得DeadLock.class锁 synchronized (DeadLock.class) { System.out.println("thread2 获取 DeadLock.class对象 锁'"); } } } catch (Exception e) { e.printStackTrace(); } System.out.println("thread2 结束!!"); }).start(); }}
某一种运行结果:
thread1 开始运行thread2 开始运行thread2 获取 Object.class对象 锁thread2 获取 DeadLock.class对象 锁'thread2 结束!! // 线程2一次性执行完,释放所有锁!thread1 获取 DeadLock.class对象 锁'thread1 获取 Object.class对象 锁thread1 结束!!
转载地址:http://ljkzi.baihongyu.com/