使用内部类实现线程死锁

线程死锁会不断消耗资源,禁止使用。本文纯属娱乐。

在使用synchronized嵌套的时候很容易出现死锁现象,因此慎用synchronized嵌套。

 

public class TestDeadLock {

  public static void main(String [] args) {
    new TestDeadLock().show();
  }

  public void show() {
    DeadLock dl = new DeadLock();
    Thread tdl1 = new Thread(dl, "老王");
    Thread tdl2 = new Thread(dl, "小王");

    tdl1.start();
    tdl2.start();
    }

  class DeadLock implements Runnable{
    private Object key1 = new Object();
    private Object key2 = new Object();
    private boolean isFlag;

    @Override
    public void run() {
      if(!isFlag) {
        isFlag = true;
        synchronized(key1) {
          System.out.println(Thread.currentThread().getName() + "拿到了key1");
          synchronized(key2) {
            System.out.println(Thread.currentThread().getName() + "拿到了key2");
          }
        }
      }else {
        isFlag = false;
        synchronized(key2) {
          System.out.println(Thread.currentThread().getName() + "拿到了key2");
          synchronized(key1) {
            System.out.println(Thread.currentThread().getName() + "拿到了key1");
          }
        }
      }
    }

    public boolean isFlag() {
      return isFlag;
    }

    public void setFlag(boolean isFlag) {
      this.isFlag = isFlag;
    }
  }
}

posted on 2018-03-09 21:19  00011101  阅读(108)  评论(0编辑  收藏  举报