关闭

生产者-消费者模式

标签: 生产者消费者waitnotify
317人阅读 评论(0) 收藏 举报
分类:
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:184314次
    • 积分:2523
    • 等级:
    • 排名:第14669名
    • 原创:80篇
    • 转载:69篇
    • 译文:0篇
    • 评论:21条
    文章分类
    最新评论