黑马程序员技术交流社区

标题: 关于生产者与消费者代码有问题?谁能帮忙解决下 [打印本页]

作者: 范靖明    时间: 2014-8-21 17:03
标题: 关于生产者与消费者代码有问题?谁能帮忙解决下
public class Resource {
private String name;
private int count = 1;
private boolean flag = false;

public synchronized void set(String name){
  while(flag){
   try {
    this.wait();
   
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+"..生产者.."+count++);
  }
  this.name = name;
  flag = true;
  this.notifyAll();
  
}
public synchronized  void out(){
  
   while(!flag){
    try {
     this.wait();
     
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"......消费者......"+count++);
   }
  
  flag = false;
  this.notifyAll();
}
public static void main(String[] args){
  Resource r = new Resource();
  Prodecter pro = new Prodecter(r);
  Consumer con = new Consumer(r);
  Thread t1 = new Thread(pro);
  Thread t2 = new Thread(con);
  t1.start();
  t2.start();
}
}
class Prodecter implements Runnable{
private Resource r;
private int count = 1;
private boolean flag = false;
public Prodecter(Resource r ){
  super();
  this.r= r ;
}
public void run(){
  for(int x=0;x<1000;x++){
    r.set("商品");
  }
}
}
class Consumer implements Runnable{
private Resource r;
private int count = 1;
private boolean flag = false;
public Consumer(Resource r ){
  super();
  this.r= r ;
}
public void run(){
  for(int x=0;x<1000;x++){
   if(x%2==0){
    r.out();
   }
  }
}
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2