A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© More 中级黑马   /  2014-7-13 06:37  /  791 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. //死锁
  2. class Test implements Runnable
  3. {
  4.         private boolean flag;
  5.         Test(boolean flag){
  6.                 this.flag=flag;
  7.         }
  8.         Object b1=new Object();//创建锁
  9.     Object b2=new Object();//创建锁
  10.         public void run(){
  11.                 if(flag)
  12.                 {
  13.                         synchronized(b1){//添加同步代码块  b1为锁
  14.                                 System.out.println("if b1");
  15.                                 synchronized(b2){///在同步代码块中嵌套同步代码块  锁为b2
  16.                                         System.out.println("if b2");
  17.                                 }
  18.                         }
  19.                 }else{
  20.                         synchronized(b2){
  21.                                 System.out.println("else b2");
  22.                                 synchronized(b1){
  23.                                         System.out.println("else b1");
  24.                                 }
  25.                         }
  26.                 }
  27.         }

  28. }

  29. class DeadLockDemo
  30. {
  31.         public static void main(String[] args)
  32.         {
  33.                 Thread t=new Thread(new Test(true));
  34.                 Thread t1=new Thread(new Test(false));
  35.                 t.start();
  36.                 t1.start();
  37.         }       
  38. }
复制代码

为什么我这里产生不了死锁??

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马