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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郝勇 中级黑马   /  2013-4-12 18:56  /  958 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 郝勇 于 2013-4-12 19:59 编辑

  1. *public class Test10 {
  2. public static void main(String[] args)
  3. {

  4. Salt s = new Salt();

  5. new Thread(new Mom(s)).start();
  6. new Thread(new Son(s)).start();
  7. }
  8. }
  9. class Salt{
  10. boolean flag = false;
  11. }
  12. class Mom implements Runnable
  13. {
  14. private Salt s;
  15. Mom(Salt s)
  16. {
  17. this.s = s;
  18. }
  19. public void run()
  20. {
  21. while(true){
  22. synchronized(s){
  23. if(s.flag){
  24. try{s.wait(1000);}
  25. catch(Exception e){}
  26. System.out.println("妈妈说:没盐了,儿子,买盐去!没法做饭了");
  27. s.flag = true;
  28. s.notify();
  29. }


  30. }
  31. }
  32. }
  33. }
  34. class Son implements Runnable{
  35. private Salt s;
  36. Son(Salt s)
  37. {
  38. this.s = s;
  39. }
  40. public void run()
  41. {
  42. while(true){
  43. synchronized(s){
  44. if(!s.flag)
  45. try{s.wait();}catch(Exception e){}
  46. System.out.println("好的,马上去买盐!!!");
  47. s.flag = false;
  48. s.notify();
  49. }
  50. }
  51. }
  52. }
复制代码

2 个回复

倒序浏览
一个小小的错误,刚刚还研究了半天。。太隐蔽了- -
在Mom方法中的if语句把所有的都括起来了,导致无法执行。。
改一下就行了。。
  1. class Mom implements Runnable

  2. {

  3. private Salt s;

  4. Mom(Salt s)

  5. {

  6. this.s = s;

  7. }

  8. public void run()

  9. {

  10. while(true){

  11. synchronized(s){

  12. if(s.flag)

  13. try{s.wait(1000);}

  14. catch(Exception e){}

  15. System.out.println("妈妈说:没盐了,儿子,买盐去!没法做饭了");

  16. s.flag = true;

  17. s.notify();

  18. }

复制代码

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1

查看全部评分

回复 使用道具 举报
恩   多谢 大神!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马