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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 苑桥别馆 中级黑马   /  2014-12-5 18:54  /  868 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Resource
  2. {
  3.          public String name;
  4.          public String sex;
  5. };
  6. class Input implements Runnable
  7. {
  8.         boolean flag=true;
  9.         private Resource r;
  10.         Input(Resource r){
  11.                 this.r=r;
  12.         }
  13.         public void run(){
  14.                 synchronized(Input.class){
  15.                                 while(true){
  16.                                         if(flag){
  17.                                                 r.name="张三";
  18.                                                 r.sex="男";
  19.                                                 flag=false;
  20.                                         }else{
  21.                                                 r.name="lili";
  22.                                                 r.sex="girl";
  23.                                                 flag=true;
  24.                         }
  25.                 }
  26.         }
  27.        
  28.         }
  29. };
  30. class Output implements Runnable
  31. {
  32.         private Resource r;
  33.         Output(Resource r){
  34.                 this.r=r;
  35.         }
  36.         public void run(){
  37.                 synchronized(Input.class){
  38.                 while(true)
  39.                         System.out.println(r.name+"--"+r.sex);
  40.                 }
  41.         }
  42.        
  43. };
  44. class ResourceMain
  45. {
  46.         public static void main(String[] args)
  47.         {
  48.                 Object objs=new Object();
  49.                 Resource r=new Resource();

  50.                 Output out=new Output(r);
  51.                 Input in=new Input(r);
  52.                 Thread t1=new Thread(in);
  53.                 Thread t2=new Thread(out);
  54.                 t1.start();
  55.                 t2.start();
  56.         }
  57. }
复制代码
如上代码,用Inout.class对象加锁同步后为什么成了死锁 ,程序不运行 ,不同步不加锁后却可以运行,这是为什么?

1 个回复

倒序浏览
while是死循环,一个线程持有锁后,进入死循环,释放不了锁啊。。。。
要把锁放在while循环里面。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马