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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© hejinzhong 中级黑马   /  2014-7-21 00:00  /  640 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 hejinzhong 于 2014-7-21 00:11 编辑
  1. <p>class Resource
  2. {
  3.         private String name;
  4.         private int count = 1;
  5.         private boolean flag;

  6.         public synchronized void set(String name)
  7.         {
  8.                 while(flag)//这里if可以吗?为啥毕姥爷视频中,讲解会有线程t1和t2都滞留在这里。难道不是一个锁?假如是一个锁的话,t1进来后,函数上锁后,t2就不可能进了函数。甚至可以说3,4线程都是不可能执行的,因为所有线程都是用的对象this锁,而对象是唯一的res。只有下次线程1获得资格执行玩后,其他线程才可能进了函数。总的来说,我的意思是这期间2,3,4线程可以获取过资格,但是不能了进函数。
  9.                         try{wait();}catch (Exception e){}
  10.                 this.name = name+"-----"+count++;
  11.                 System.out.println(Thread.currentThread().getName()+"--生产者--"+this.name);
  12.                 flag = true;
  13.                 this.notifyAll();
  14.         }

  15.         public synchronized void out()
  16.         {
  17.                 while(!flag)//if?讲解会有线程t3和t4都滞留在这里。难道不是一个锁?和上面一样的问题。
  18.                         try{wait();}catch (Exception e){}
  19.                 System.out.println(Thread.currentThread().getName()+"--消费者-------"+name);
  20.                 flag =false;
  21.                 this.notifyAll();
  22.         }
  23. }

  24. class Producer implements Runnable
  25. {
  26.         private Resource res;
  27.         Producer(Resource res)
  28.         {
  29.                 this.res=res;
  30.         }
  31.         public void run()
  32.         {
  33.                 while(true)
  34.                         res.set("--商品--");
  35.         }
  36. }

  37. class Consumer implements Runnable
  38. {
  39.         private Resource res;
  40.         Consumer(Resource res)
  41.         {
  42.                 this.res=res;
  43.         }
  44.         public void run()
  45.         {
  46.                 while(true)
  47.                         res.out();
  48.         }
  49. }
  50. class ProducerConsumerDemo
  51. {
  52.         public static void main(String[] args)
  53.         {
  54.                 Resource res = new Resource();

  55.                 Producer pro = new Producer(res);
  56.                 Consumer con = new Consumer(res);

  57.                 Thread t1 = new Thread(pro);
  58.                 Thread t2 = new Thread(pro);
  59.                 Thread t3 = new Thread(con);
  60.                 Thread t4 = new Thread(con);

  61.                 t1.start();
  62.                 t2.start();
  63.                 t3.start();
  64.                 t4.start();
  65.         }
  66. }</p>
复制代码

1 个回复

倒序浏览
知道了,刚想通了,因为wait()之后他会释放锁。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马