消费者与生产者模型

小明往一张银行卡里面存钱,小美和小娟从这张银行卡中取钱。小美和小娟每次随机取50-100块钱,当里面没钱后,通知小明存钱。小明每次存1000元,存完后通知小美和小娟取钱。

import java.util.Random;

public class Resource {

	private int money;
	private boolean isEmpty = true;

	public void push(int money) {
		synchronized ("") {
			if (!isEmpty) {
				try {
					"".wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			this.money += money;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "存了" + money + "元,还剩"+this.money);
			isEmpty = false;
			"".notify();
		}
	}

	public void pop() {
		synchronized ("") {
			if (isEmpty) {
				try {
					"".wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			Random r = new Random();
			int hua = r.nextInt(50) + 50;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (money < hua) {
				isEmpty = true;
				"".notify();
			} else {
				money -= hua;
				System.out.println(Thread.currentThread().getName() + "花了" + hua + "元,还剩" + money + "元");

			}
		}
	}
}

public class Consumer implements Runnable{
	
	private Resource res;

	public Consumer(Resource res) {
		this.res = res;

	}

	@Override
	public void run() {
		while(true) {
			res.pop();
		}		
	}
}

public class Producer implements Runnable{

	private Resource res;

	public Producer(Resource res) {
		this.res = res;
	}
	@Override
	public void run() {
		while(true) {
			res.push(1000);
		}
	}
}
public class Test {

	public static void main(String[] args) {
		Resource res = new Resource();
		
		new Thread(new Consumer(res),"小美").start();
		new Thread(new Consumer(res),"小娟").start();
		
		new Thread(new Producer(res),"小明").start();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值