黑马程序员技术交流社区

标题: 请帮忙看下以下代码为什么会发生死锁(多线程 唤醒等待机制) [打印本页]

作者: 唐志海    时间: 2013-11-19 19:01
标题: 请帮忙看下以下代码为什么会发生死锁(多线程 唤醒等待机制)
  1. class resouse
  2. {
  3.         private String name;
  4.         private String sex;
  5.         private boolean flag=false;
  6.         public synchronized void set(String name,String sex)
  7.         {
  8.                 while(flag)
  9.                         try{this.wait();}
  10.                 catch(Exception e)
  11.                 {
  12.                
  13.                 }
  14.                 this.name=name;
  15.                 this.sex=sex;
  16.                 System.out.println(name+"%……………………………………"+sex);
  17.                 flag=true;
  18.                 this.notifyAll();
  19.                
  20.         }
  21.         public synchronized void prit()
  22.         {
  23.                 while(!flag)
  24.                         try{this.wait();}
  25.                 catch(Exception e){}
  26.                
  27.                 System.out.println(name+"....."+sex);
  28.                 flag=false;
  29.                 this.notifyAll();
  30.                
  31.         }
  32.        
  33. }
  34. class Shengchang implements Runnable
  35. {
  36.         private resouse r;
  37.         Shengchang(resouse r)
  38.         {
  39.                 this.r=r;
  40.         }
  41.         public void run()
  42.         {
  43.                
  44.                 while(true)
  45.                 {
  46.                        
  47.                                 r.set("李四","男");
  48.                
  49.                 }
  50. }
  51.        
  52. }
  53. class outprint implements Runnable
  54. {
  55.         private resouse r;
  56.         outprint(resouse r)
  57.         {
  58.                 this.r=r;
  59.         }
  60.         public void run()
  61.         {
  62.                 r.prit();
  63.         }
  64. }

  65.        
  66. public class Dengdai {
  67.         public static void main(String[] args)
  68.         {
  69.                 resouse r=new resouse();
  70.                
  71.                 Shengchang in=new Shengchang(r);
  72.                 outprint ou=new outprint(r);
  73.                 Thread t=new Thread(in);
  74.                 Thread t1=new Thread(in);
  75.                 Thread t2=new Thread(ou);
  76.                 Thread t3=new Thread(ou);
  77.                 t1.start();
  78.                 t.start();
  79.                
  80.                 t2.start();
  81.                 t3.start();
  82.         }
  83. }
复制代码

作者: hurryup    时间: 2013-11-19 19:57
资源方法里面少大括弧。
作者: 唐志海    时间: 2013-11-19 20:48
没有吧,少个大括弧那编译都不会通过啊。
作者: 黄炳期    时间: 2013-11-20 09:33
如果问题已经解决,请及时修改主题为“提问结束”。
修改主题的方法链接
http://bbs.itheima.com/thread-89313-1-1.html





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