java线程(生产者/消费者)

import java.util.ArrayList;
import java.util.List;

/**
 * 消费者/生产者模式 问题:
 *  1.一个共同容量确定的仓库,
 *  2.生产者只管生产物品放到仓库,若仓库库满则等待,若库未满,继续生产放入,
 *  3.消费者只管从仓库区物品,若库空则等待,若库未空,则取
 *  4.消费者和生产者,相互不关联
 *
 * 代码: 1.创建物品类 2.容量一定的仓库类(存取) 3.消费者类(继承Thread) 4.生产者类(继承Thread)
 *
 */


// 物品类
class Goods {
      public   int id ;
    public Goods(){};
      public Goods( int id ) {
            this . id = id ;
     }

      public String toString() {
            return "goods" + id ;
     }
}



// 仓库(物品类)
class Store {
      //用于存放goods的集合
      private Goods[] lst = new Goods[5];
      int index =0;
      //仓库容量的确定
      //放
      public synchronized void put(Goods goods ) {
           System. out .println( "put" + goods . id );
            while ( index == lst . length ){
                 try {
                      this .wait();
                } catch (InterruptedException e ) {
                      // TODO Auto-generated catch block
                      e .printStackTrace();
                }    
           }
            this .notify();
            lst [ index ]= goods ;
            index ++;   
     }
      //取
      public synchronized Goods take(){    
            while ( index ==0){
                 try {
                      this .wait();
                } catch (InterruptedException e ) {
                      // TODO Auto-generated catch block
                      e .printStackTrace();
                }
           }
            index --;
            this .notify();
            return lst [ index ];
           
     }
}


//生产者
class Producer extends Thread{
      private Store store ;
      public void setStore(Store store ){
            this . store = store ;
     }
      @Override
      public void run() {
            //生产物品
                   for ( int i =0; i <30; i ++){    
                     Goods g = new Goods( i );
                    store .put( g );
                   }       
     }
     
}


//消费者
class Consumer extends   Thread {
      private Store store
      public void setStore(Store store ){
            this . store = store ;
     }
      @Override
      public void run() {
     
            for ( int i =0; i <30; i ++){

                System. out .println( "take" + store .take(). id );
     
        }
     }
     
}


//测试
class   ProduceConsume {
     
     
      public static void main(String[] args ) {
         Store store = new Store();
           Producer producer = new Producer();
           Consumer consumer = new Consumer();
            producer .setStore( store );
            consumer .setStore( store );
            producer .start();
            consumer .start();    
     }
     
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值