生产者与消费者的案例

/**
 *  要点
 *  1. sleep和wait的区别 
 */

public class Demo {

	public static void main(String[] args) {
		Food f = new Food();
		Producter p = new Producter(f);
		Consumer c = new Consumer(f);
		new Thread(p).start();
		new Thread(c).start();
	}

}

/**
 * 生产者
 */
class Producter implements Runnable {
	private Food food;

	public Producter(Food food) {
		this.food = food;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			if (i % 2 == 0) {
				food.set("西红柿炒蕃茄", "这个好吃");
			} else {
				food.set("土豆炒薯仔", "啃爹食物");
			}
		}
	}
}

/**
 * 消费者
 */
class Consumer implements Runnable {
	private Food food;

	public Consumer(Food food) {
		this.food = food;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			food.get();
		}
	}
}

/**
 * 产品
 */
class Food {
	private String name;
	private String content;
	private boolean flag = true; //表示可以消费

	public Food() {
		super();
	}

	public Food(String name, String content) {
		super();
		this.name = name;
		this.content = content;
	}

	// 生产产品
	public synchronized void set(String name, String content) {
		if (!flag) {
			try {
				this.wait(); //让当前线程进入等待池等待,
								//没有设定时间,需要其他线程唤醒,
								//释放对象锁,让出CUP
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.setName(name);
		try {
			Thread.sleep(300);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.setContent(content);
		flag = false; //表示可以消费
		this.notify(); //唤醒在该监视器上的一个线程
	}

	public synchronized void get() {
		if (flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(300);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(this.getName() + ":" + this.getContent());
		flag = true; //表示可以生产 
		this.notify();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值