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

 定义一个商品类,里面定义生产方法,消费方法,

定义一个生产者类,一个消费者类,传入 商品类对象

分别调用生产方法,消费方法

class Goods{
	//商品名称
	private String goodsName;
	//商品库存
	private int count;
	//生产方法
	public synchronized void set(String name) throws InterruptedException {
		while(this.count>0) {
			System.out.println("还有库存,等待消费者");
			wait();
		}
		this.goodsName=name;
		this.count++;
		Thread.sleep(1000);
		System.out.println(Thread.currentThread().getName());
		System.out.println("生产"+toString());
		System.out.println("=========================================");
		//生产完后通知消费者进程可以消费了
		notifyAll();
	}
	//消费方法
	public synchronized void get() throws InterruptedException {
		while(this.count==0) {
			System.out.println("没有库存了,等待生产者");
			wait();
		}
		this.count--;
		Thread.sleep(1000);
		System.out.println(Thread.currentThread().getName());
		System.out.println("消费"+toString());
		System.out.println("=========================================");
		//消费完后通知生产者进程可以开始生产了
		notifyAll();
	}
	@Override
	public String toString() {
		return "Goods [goodsName=" + goodsName + ", count=" + count + "]";
	}
	
}
//生产者类
class producer implements Runnable{
	private Goods goods;
	public producer(Goods goods) {
		super();
		this.goods = goods;
	}
	public void run() {
		while(true) {
		try {
			this.goods.set("奔驰c200l一辆");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
	}
}
//消费者类
class Consumer implements Runnable{
	private Goods goods;

	public Consumer(Goods goods) {
		super();
		this.goods = goods;
	}
	public void run() {
		while(true) {
		try {
			this.goods.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
	}
}
public  class Test {
	public static void main(String[] args) {
		Goods goods=new Goods();
		List<Thread> threadlist=new ArrayList<>();
		for(int i=0;i<10;i++) {
			Thread producerthread=new Thread(new producer(goods));
			producerthread.setName("生产者线程"+i);
			threadlist.add(producerthread);
		}
		for(int i=0;i<5;i++) {
			Thread consumerthread=new Thread(new Consumer(goods));
			consumerthread.setName("消费者线程"+i);
			threadlist.add(consumerthread);
		}
		for (Thread thread : threadlist) {
			thread.start();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值