Java并发协作——生产者、消费者模型

概述

对于多线程程序来说,生产者和消费者模型是非常经典的模型。更加准确的说,应该叫“生产者-消费者-仓库模型”。离开了仓库,生产者、消费者就缺少了共用的存储空间,也就不存在并非协作的问题了。

示例

定义一个场景。一个仓库只允许存放10件商品,生产者每次可以向其中放入一个商品,消费者可以每次从其中取出一个商品。同时,需要注意以下4点:
1.  同一时间内只能有一个生产者生产,生产方法需要加锁synchronized。
2.  同一时间内只能有一个消费者消费,消费方法需要加锁synchronized。
3.  仓库为空时,消费者不能继续消费。消费者消费前需要循环判断当前仓库状态是否为空,空的话则消费线程需要wait,释放锁允许其他同步方法执行。
4.  仓库为满时,生产者不能继续生产,生产者生产钱需要循环判断当前仓库状态是否为满,满的话则生产线程需要wait,释放锁允许其他同步方法执行。

示例代码如下:
public class Concurrence {
	public static void main(String[] args) {
		WareHouse wareHouse = new WareHouse();
		Producer producer = new Producer(wareHouse);
		Consumer consumer = new Consumer(wareHouse);

		new Thread(producer).start();
		new Thread(consumer).start();
	}
}

class WareHouse {
	private static final int STORE_SIZE = 10;
	private String[] storeProducts = new String[STORE_SIZE];
	private int index = 0;

	public void pushProduct(String product) {
		synchronized (this) {
			while (index == STORE_SIZE) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			storeProducts[index++] = product;
			this.notify();

			System.out.println("生产了: " + product + " , 目前仓库里共: " + index
					+ " 个货物");
		}
	}

	public synchronized String getProduct() {
		synchronized (this) {
			while (index == 0) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			String product = storeProducts[index - 1];
			index--;
			System.out.println("消费了: " + product + ", 目前仓库里共: " + index
					+ " 个货物");
			this.notify();
			return product;
		}
	}
}

class Producer implements Runnable {
	WareHouse wareHouse;

	public Producer(WareHouse wh) {
		this.wareHouse = wh;
	}

	@Override
	public void run() {
		for (int i = 0; i < 40; i++) {
			String product = "product" + i;
			this.wareHouse.pushProduct(product);
		}
	}
}

class Consumer implements Runnable {
	WareHouse wareHouse;

	public Consumer(WareHouse wh) {
		this.wareHouse = wh;
	}

	@Override
	public void run() {
		for (int i = 0; i < 40; i++) {
			this.wareHouse.getProduct();
		}
	}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值