生产消费者模型

生产者与消费者模型,使用合理的线程池来实现10个生产者与5个消费者并发处理商品的售卖。 
import java.util.ArrayList;
import java.util.List;

class Goods{
    //产品名称
    private String name;
    //产品数量
    private int  count;
    //生产方法
    public synchronized void set(String name) throws InterruptedException {
        while(count>0) {
            wait();
        }
        this.name=name;
        this.count=count+1;
        System.out.println(toString());
        notify();
    }
    //消费方法
    public synchronized void get() throws InterruptedException {
        while(count==0) {
            wait();
        }
        this.count=this.count-1;    
        System.out.println(toString());
        notify();
    }
    @Override
    public String toString() {
        return Thread.currentThread().getName()+"产品:"+name+"   "+"数量为:"+count;
        
    }
}
//生产者类
class Producer implements Runnable{
    private Goods goods;
    public Producer(Goods goods) { //生产者的构造方法是为了限制传入的参数是Good类的对象,使得生产者消费者都是用的是GOOD对象
        super();
        this.goods=goods;
    }
    @Override
    public void run() {
        while(true) {
        try {
            this.goods.set("代码一段");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
    
}
//消费者类
class Cusumer implements Runnable{
    private Goods goods;
    public  Cusumer(Goods goods) {
    super();
    this.goods=goods;
    }
    @Override
    public void run() {
        while(true) {
        try {
            this.goods.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    }
    
}

public class ShengChanXiaoFeiZhe {
public static void main(String[] args) {
    
    List<Thread> list=new ArrayList<>();
    Goods goods=new Goods();
    //十个消费者线程
    for(int i=0;i<10;i++) {
        Producer producer=new Producer(goods);
        Thread thread=new Thread(producer,"消费者-"+i);
        list.add(thread);
    }
    for(int i=0;i<5;i++) {
        Cusumer cusumer=new Cusumer(goods);
        Thread thread=new Thread(cusumer,"生产者-"+i);
        list.add(thread);
    }
    for(Thread thread :list) {
        thread.start();
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值