生产者-消费者模式

package thread.cusproc;
/**
 * 仓库类,在这里面实现生产和消费。同步互斥。
 * @author sunniwell
 *
 */
public class WareHouse {
/**
* 最大仓储量
*/
private static final int MAX_COUNT = 100;

private int currentCount;

public WareHouse(int currentCount){
this.currentCount = currentCount;
}

/**
* 生产
* @param needNum 需要生产的数量
*/
public synchronized void produce(int needNum){
while(currentCount+needNum > MAX_COUNT){
System.out.println("要生产的数量("+needNum+")超过了当前仓库可产量("+(MAX_COUNT-currentCount)+"),暂停生产。");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//简单地更改库存量,表示生产业务。
currentCount += needNum;
System.out.println("生产了"+needNum+"个产品,当前库存量为"+currentCount);
notifyAll();
}

/**
* 消费
* @param needNum 需要消费的数量
*/
public synchronized void consume(int needNum){
while(currentCount < needNum){
System.out.println("要消费的数量("+needNum+")超过了当前仓库量("+(currentCount)+"),暂停消费。");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//简单地更改库存量,表示消费业务。
currentCount -= needNum;
System.out.println("消费了"+needNum+"个产品,当前库存量为"+currentCount);
notifyAll();
}

}


package thread.cusproc;

public class Producer extends Thread {
private WareHouse house;
private int needNum;

public Producer(WareHouse house, int needNum){
this.house = house;
this.needNum = needNum;
}

@Override
public void run() {
house.produce(needNum);
}

}


package thread.cusproc;

public class Consumer extends Thread {
private WareHouse house;
private int needNum;

public Consumer(WareHouse house, int needNum){
this.house = house;
this.needNum = needNum;
}

@Override
public void run() {
house.consume(needNum);
}

}


package thread.cusproc;

public class Test {
public static void main(String[] args) {
WareHouse house = new WareHouse(20);

Consumer c1 = new Consumer(house, 30);
Consumer c2 = new Consumer(house, 60);
Consumer c3 = new Consumer(house, 20);

Producer p1 = new Producer(house, 40);
Producer p2 = new Producer(house, 10);
Producer p3 = new Producer(house, 10);
Producer p4 = new Producer(house, 15);
Producer p5 = new Producer(house, 50);

c1.start();
c2.start();
c3.start();

p1.start();
p2.start();
p3.start();
p4.start();
p5.start();

}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值