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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 rolan 于 2015-4-29 22:47 编辑

关于生产者模式,我写的代码和老师的一样,为什么会有这么多错误啊?求指导
  1. class ProducerConsumerDemo{
  2.         public static void main(String[] args){
  3.                 Resource re=new Resource();
  4.                 Producer pro=new Producer(re);
  5.                 Consumer con=new Consumer(re);
  6.                 Thread t1=new Thread(pro);
  7.                 Thread t2=new Thread(con);
  8.                 t1.start();
  9.                 t2.start();
  10.         }
  11. }
  12. class Resource{
  13.         private String name;
  14.         private int count=1;
  15.         boolean flag=false;
  16.         public synchronized void set(String name){
  17.                 if(flag){
  18.                         try{
  19.                                 wait();
  20.                                 }catch(Exception e){
  21.                 }
  22.                 }
  23.                 this.name=name+"-------"+count++;
  24.                 System.out.println("-----生产者------"+Thread.currentThread().getName()+name);
  25.                 flag=true;
  26.                 notify();
  27.         }

  28.         public synchronized void out(){
  29.                 if(!flag){
  30.                         try{wait();
  31.                                 }catch(Exception e){
  32.                                                 }
  33.                 }
  34.                 System.out.println("-----消费者------"+Thread.currentThread().getName()+name);
  35.                 flag=false;
  36.                 notify();
  37.         }
  38. }
  39. class Producer implements Runnable{
  40.         private Resource res;
  41.         Producer(Resource res){
  42.                 this.res=res;}
  43.         public void run(){
  44.                 while(true){
  45.                         re.set("商品");
  46.                         
  47.                 }
  48.         }
  49. }
  50. class Consumer implements Runnable{
  51.         private Resource res;
  52.         Consumer(Resource res){
  53.                 this.res=res;}
  54.                 public void run(){
  55.                 while(true){
  56.                         re.out();
  57.                         
  58.                 }
  59.         }
  60. }
复制代码

3 个回复

倒序浏览
这个是提示的错误,类重复什么的

111.jpg (88.21 KB, 下载次数: 14)

111.jpg
回复 使用道具 举报
学习初期经常出现“我的代码跟老师的一样”这样这样的幻觉

点评

正解。。。  发表于 2015-4-26 18:07
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马