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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘文飞 中级黑马   /  2012-11-17 14:25  /  850 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 刘文飞 于 2012-11-17 15:51 编辑
  1. class Resource
  2. {
  3. private String name;
  4. private String sex;
  5. private boolean flag;
  6. public void setNameAndSex(String name,String sex)
  7. {
  8. this.name = name;
  9. this.sex = sex;
  10. }
  11. public void setFlag(boolean flag)
  12. {
  13. this.flag = flag;
  14. }
  15. public boolean getFlag()
  16. {
  17. return this.flag;
  18. }
  19. public void print()
  20. {
  21. System.out.println(this.name + "-------" + this.sex);
  22. }
  23. }
  24. class Input implements Runnable{
  25. private Resource res;
  26. public Input(Resource res)
  27. {
  28. this.res = res;
  29. }
  30. private int x = 0;
  31. public void run()
  32. {
  33. while(true)
  34. {
  35. synchronized(res)
  36. {
  37. if(res.getFlag())
  38. {
  39. try{
  40. res.wait();
  41. }
  42. catch(InterruptedException e)
  43. {
  44. e.printStackTrace();
  45. }

  46. }
  47. if(x == 0)
  48. {
  49. res.setNameAndSex("hezi","boy");
  50. }
  51. else
  52. {
  53. res.setNameAndSex("莉莉","女孩");
  54. }
  55. x = (x + 1)/2;
  56. res.setFlag(true);
  57. res.notify();
  58. }
  59. }
  60. }
  61. }
  62. class Output implements Runnable
  63. {
  64. private Resource res;
  65. public Output(Resource res)
  66. {
  67. this.res = res;
  68. }
  69. public void run()
  70. {
  71. while(true)
  72. {
  73. synchronized(res)
  74. {
  75. if(!res.getFlag())
  76. {
  77. try{
  78. res.wait();
  79. }
  80. catch(InterruptedException e)
  81. {
  82. e.printStackTrace();
  83. }
  84. }
  85. res.print();
  86. res.setFlag(false);
  87. res.notify();
  88. }
  89. }
  90. }
  91. }
  92. public class SynchronizedDemo01
  93. {
  94. public static void main(String[] args)
  95. {
  96. Input in = new Input(new Resource());
  97. Output out = new Output(new Resource());
  98. Thread t1 = new Thread(in);
  99. Thread t2 = new Thread(out);
  100. t1.start();
  101. t2.start();
  102. }
  103. }
复制代码
编译没问题,运行也没有问题,就是没有输出啊。。

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

1 个回复

倒序浏览
睡了一觉醒来自个发现问题了,
Input in = new Input(new Resource());

Output out = new Output(new Resource());

这里两个匿名对象表示的不是同一个对象。。。。
两个线程都在那等着呢
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马