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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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();
   }
  }
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马