java:经典消费生成者

产品类:

public class Info {
	
	private String title = "生产";	
	private String content = "生产罐头";
	private boolean flag = false; // 默认是false

	/*
	 * 1、flag = true,表示可以生产,但是不能取走
	 * 
	 * 2、flag = false,表示可以取走,但是不能生产
	 */
	public synchronized void set(String title, String content) {
		if (flag == false) {// 已经生产过了,需要等待
			try {
				super.wait(); // 等待
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.setTitle(title);		
		this.setContent(content);
		this.flag = false;// 表示不能生产了
		super.notify(); // 唤醒其他等待的线程
	}

	public synchronized void get() {
		if (flag == true) {// 表示不能取
			try {
				super.wait(); // 等待
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(this.title + " --> " + this.content);
		this.flag = true;// 表示不能取走了
		super.notify(); // 唤醒
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

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

  

生产类:

public class Producer implements Runnable {
	
	private Info info = null;

	public Producer(Info info) {
		this.info = info;
	}

	@Override
	public void run() {
		// TODO 自动生成的方法存根
		for (int x = 0; x < 100; x++) { // 不断的生产
			if (x % 2 == 0) {// 是奇数
				this.info.set("消费", "购买罐头");
			} else {
				this.info.set("生产", "生产罐头");
			}
		}	
	}

}

  

消费类:

public class Consumer implements Runnable {

	private Info info = null;

	public Consumer(Info info) {
		this.info = info;
	}
	
	@Override
	public void run() {
		// TODO 自动生成的方法存根
		for (int x = 0; x < 100; x++) {
			this.info.get();
		}
	}

}

  

测试:

public class TestInfo3 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根

		Info info = new Info();
		Producer pro = new Producer(info); // 实例化生产者对象
		Consumer con = new Consumer(info); // 实例化消费者对象
		new Thread(pro).start(); // 启动线程
		new Thread(con).start(); // 启动线程
		
	}

}

  

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值