β

Java–死锁以及死锁的排查

Harries Blog™ 6 阅读

清单一

public class SynchronizedDeadLock {

  private static final Object lockA = new Object();
  private static final Object lockB = new Object();

  /**
   * ThreadA先获取lockA,在获取lockB
   */
  private static class ThreadA extends java.lang.Thread {

    @Override
    public void run() {
      // 获取临界区A
      synchronized (lockA) {
        System.out.println("get lockA success");
        // 模拟耗时操作
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        // 获取临界区B
        synchronized (lockB) {
          System.out.println("get lockB success");
        }
      }
    }
  }

  /**
   * ThreadB先获取lockB,在获取lockA
   */
  private static class ThreadB extends java.lang.Thread {

    @Override
    public void run() {
      // 获取临界区A
      synchronized (lockB) {
        System.out.println("get lockB success");
        // 模拟耗时操作
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        // 获取临界区B
        synchronized (lockA) {
          System.out.println("get lockA success");
        }
      }
    }
  }
}
作者:Harries Blog™
追心中的海,逐世界的梦
原文地址:Java–死锁以及死锁的排查, 感谢原作者分享。

发表评论