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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 袭喜悦 中级黑马   /  2013-2-13 20:45  /  1310 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Resource
  2. {
  3. private String name;
  4. private int count=1;
  5. private boolean flag=false;
  6. public synchronized void set(String name)
  7. {
  8. while(flag)
  9. try{this.wait();}catch(Exception e){}
  10. this.name=name+"--"+count++;
  11. System.out.println(Thread.currentThread().getName()+"...生产者......."+this.name);
  12. flag=true;
  13. this.notify();
  14. }
  15. public synchronized void out(){
  16. while(!flag)
  17. try{this.wait();}catch(Exception e){}
  18. System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
  19. flag=false;
  20. this.notify();
  21. }
  22. }
  23. class ProducerConsumerDemo
  24. {
  25. public static void main(String[] args)
  26. {
  27. Resource r=new Resource();
  28. Producer pro=new Producer(r);
  29. Consumer con=new Consumer(r);
  30. Thread t1=new Thread(pro);
  31. Thread t2=new Thread(con);
  32. t1.start();
  33. t2.start();

  34. }
  35. }
  36. class Producer implements Runnable
  37. {
  38. private Resource res;
  39. Producer(Resource res)
  40. {
  41. this.res=res;
  42. }
  43. public void run()
  44. {
  45. while(true)
  46. {
  47. res.set("+商品+1");
  48. }
  49. }
  50. }
  51. class Consumer implements Runnable
  52. {
  53. private Resource res;
  54. Consumer(Resource res)
  55. {
  56. this.res=res;
  57. }
  58. public void run()
  59. {
  60. while(true)
  61. {
  62. res.out();
  63. }
  64. }
  65. }
复制代码
使用notify();为什么没有出现全部等待的情况,打印结构竟然跟notifyall()一样的

2 个回复

正序浏览
石鲁杰 发表于 2013-2-13 20:53
楼主只有两个线程,生产完,接着就被消费了,当然不会出现被等待的情况,多加几个线程就看到效果了 ...

:L过年过的混乱了。。。。晕死了
回复 使用道具 举报
  1. class ProducerConsumerDemo
  2. {
  3. public static void main(String[] args)
  4. {
  5. Resource r=new Resource();
  6. Producer pro=new Producer(r);
  7. Consumer con=new Consumer(r);
  8. Thread t1=new Thread(pro);
  9. Thread t2=new Thread(con);
  10. Thread t3 = new Thread(con);
  11. Thread t4 = new Thread(con);
  12. t1.start();
  13. t2.start();
  14. t3.start();
  15. t4.start();
  16. }
  17. }
复制代码
楼主只有两个线程,生产完,接着就被消费了,当然不会出现被等待的情况,多加几个线程就看到效果了

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马