黑马程序员技术交流社区

标题: 关于多线程产生死锁的问题 [打印本页]

作者: More    时间: 2014-7-13 06:37
标题: 关于多线程产生死锁的问题
  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. }
复制代码

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




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2