【Java 多线程】简单生产者消费者模型

package LessonTwo;

public class producerCustomer02 {

	public static void main(String[] args) {
		database d = new database();
		Thread pr = new Thread(new producer(d));
		Thread cu = new Thread(new customer(d));

		pr.start();
		cu.start();
	}
}

class rice{
	public static int id = 0;

	rice(int dex){
		id = dex;
	}
}

class database{
	private static int index = 0;
	rice[] mRice =  new rice[6];

	public synchronized void push (rice rc){
		
		while (index == mRice.length){
			System.out.println("****** 仓库已经满满的了 *******");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		this.notify();
		mRice[index++] = rc;
		
		System.out.println(("生产了产品 "+rc.id+" 仓库总数为:"+index));
	}

	synchronized rice pop(){
		while (index == 0){
			System.out.println("******** 仓库空空如也 ********");
			
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		this.notify();
		--index;
		rice rc = mRice[index];
		System.out.println(("消费了产品 "+rc.id+" 仓库总数为:"+index));
		
		return rc;
	}
}

class producer implements Runnable{
	database db = new database();

	public producer(database dab){
		db = dab;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 20; i++){
			db.push(new rice(i));

			try {
				Thread.sleep((int) (Math.random()*500));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

class customer implements Runnable{
	database db = new database();

	public customer(database dab){
		db = dab;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 20; i++){
			db.pop();

			try {
				Thread.sleep((int) (Math.random()*500));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


生产者生产大米存入仓库,消费者从仓库中消费大米。

生产者消费者使用多线程模拟,仓库中可以存放6袋大米。当仓库存满时,生产者线程 等待,同时释放线程锁。

消费者线程继续运行,同时唤醒线程,达到模拟生产者消费者的效果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值