生产者/消费者实现方式一: 管程法

package com.yunding.concurrent;

/**
 * 生产者/消费者实现方式一: 管程法
 * 
 * @author beOkWithAnything
 *
 */
public class Test {

	public static void main(String[] args) {
		Container container = new Container();
		new Productor(container).start();
		new Consumer(container).start();
	}

}

// 生产者
class Productor extends Thread {
	// 持有对产品容器的引用
	Container container;

	public Productor(Container container) {
		this.container = container;
	}

	@Override
	public void run() {
		// 生产
		for (int i = 0; i < 50; i++) {
			container.produce(new Product(i));
		}
	}
}

// 消费者
class Consumer extends Thread {
	// 持有对产品容器的引用
	Container container;

	public Consumer(Container container) {
		this.container = container;
	}

	@Override
	public void run() {
		// 消费
		for (int i = 0; i < 50; i++) {
			container.getProduct();
		}
	}
}

// 缓冲区
class Container {
	// 计数器
	int count = 0;
	// 存储容器
	Product[] products = new Product[10];

	// 生产产品
	synchronized void produce(Product product) {
		// 缓冲区已经填满,不能再生产
		if (count == products.length) {
			try {
				// 线程阻塞
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// 生产了产品
		products[count] = product;
		count++;
		System.out.println("生产-- 》 第" + product.id + "个产品");
		// 通知消费者可以购买了
		this.notifyAll();
	}

	// 获取产品
	synchronized Product getProduct() {
		// 如果没有产品
		if (count == 0) {
			try {
				// 线程阻塞
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// 消费了
		count--;
		Product product = products[count];
		System.out.println("消费-- 》 第" + product.id + "个产品");
		// 通知生产者可以开始生产了
		this.notifyAll();
		return product;
	}
}

// 产品
class Product {
	int id;

	public Product(int id) {
		this.id = id;
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beOkWithAnything

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值