咬定青山不放松,立根原在破岩中。千磨万击还坚劲,任尔东西南北风。

《竹石》 点击图标与我实时聊天

生产者-消费者(线程问题)

//生产者-消费者 问题

public class Pro_Cus {
 
 public static void main(String[] args){
  
  Container con=new Container();
  
  Producer p=new Producer(con);
  Customer c=new Customer(con);
  
  new Thread(p).start();//各定义了两个线程,可以多个线程
  new Thread(c).start();
  new Thread(p).start();
  new Thread(c).start();
 }

}
//产品
class Product{
 
 int id;
 public Product(int id){
  this.id=id;
 }
 
 public String toString(){
  return ""+this.id;
 }
 
}
//装产品容器
class Container{
 Product[] num=new Product[10];
 int index=0;
 
 public synchronized void push(Product pro){
  
  while(index==num.length){
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.notifyAll();  //倘若只有一个消费线程则,用this.notify();
  num[index]=pro;
  index++;
 }
 
 public synchronized Product pop(){
  
  while(index==0){
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  this.notifyAll();//倘若只有一个生产者线程,用this.notify
    index--;
    return num[index];
 
 }
 
}

//生产者
class Producer implements Runnable{
 
 Container con=null;
 
 public Producer(Container con){
  this.con=con;
 }
 public void run(){
    for(int i=0;i<20;i++){
    
     try {
   Thread.sleep(10); //10毫秒生产一个
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
     con.push(new Product(i));
    
     System.out.println("生产了产品:"+i);
    }
 }
 
}

//消费者
class Customer implements Runnable{
 
 Container con=null;
 
 public Customer(Container con){
  this.con=con;
 }
 public void run(){
    for(int i=0;i<20;i++){
    
     try {
    Thread.sleep((int)(Math.random()*3000));//随机小于等于3秒消费一个
   //Thread.sleep(3000);//为3秒消费一个用,这种形式
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
     Product pro=con.pop();
     System.out.println("消费了产品:"+pro);
    }
 }
 
}

 

 

 

 

 

 

 

 


 

posted on 2009-11-11 13:17 任小为 阅读(297) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航:
 

导航

留言簿

随笔分类

积分与排名

最新评论

阅读排行榜