Java多线程下的生产者消费者模式

  用多线程的生产者消费者模式实现工厂的面包运到超市,顾客去超市购买,超市每次最大存储6个面包。

public class Test1Consumer {
	public static void main(String[] args) {
		Supermarkt s = new Supermarkt();

		Factory f = new Factory(s);
		Consumer c = new Consumer(s);

		Thread t = new Thread(f, "工厂");
		Thread t1 = new Thread(c, "顾客");

		t.start();
		t1.start();
	}
}

class Brand {
	int id;
	String name;

	public Brand(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

class Supermarkt {
	Brand b[] = new Brand[6];
	int index = -1;

	// 运面包
	public synchronized void addBrand(Brand brand) throws InterruptedException {
		if (index >= 5) {
			this.wait();
		}
		index++;
		b[index] = brand;
		System.out.println(Thread.currentThread().getName() + "卖了"
				+ brand.getId() + "个" + brand.getName() + "的面包,超市一共还有"
				+ (index + 1) + "个");
		this.notifyAll();
	}

	// 卖面包
	public synchronized void saleBrand() throws InterruptedException {
		if (index <= -1) {
			this.wait();
		}
		// 打印卖出去面包的信息
		System.out.println(Thread.currentThread().getName() + "买掉了"
				+ b[index].getId() + "个" + b[index].getName() + "的面包,超市还剩下"
				+ (index) + "个");
		index--;
		this.notifyAll();
	}

}

class Factory implements Runnable {
	Supermarkt markt;

	public Factory(Supermarkt markt) {
		super();
		this.markt = markt;
	}

	@Override
	public void run() {
		for (int i = 0; i < 80; i++) {
			try {
				markt.addBrand(new Brand(1, "难吃"));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

class Consumer implements Runnable {
	Supermarkt sup;

	public Consumer(Supermarkt sup) {
		super();
		this.sup = sup;
	}

	@Override
	public void run() {
		for (int i = 0; i < 80; i++) {
			try {
				sup.saleBrand();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值