日期:2014-05-20 浏览次数:20681 次
package com.jh.java.thread;
/**
* 模拟场景:
*
* 生产者和消费者模式
* 库存为0,首先开始生产,最大库存为100。库存将满时 开始消费。
* 消费到库存 不够时 则扩大再生产。
* 如此反复
* @author JIHAN
*
*/
public class MyTest3 {
public static void main(String[] args) {
Storehouse house = new Storehouse();
new Thread(new Producer(house)).start();
new Thread(new Consumer(house)).start();
}
}
/**
* 仓库
* @author JIHAN
*
*/
class Storehouse{
private int stockMax = 100;
private int stock = 0;
public synchronized void produce(int i) {
if(stock+i >stockMax) {
System.out.println("警告: 若生产" + i + "个,库存"+stock+" 将已满。。。暂停生产 。。。 ");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stock += i;
System.out.println(Thread.currentThread().getName() + " 生产 " + i + "个, 当前库存 " + stock);
notifyAll();
}
public synchronized void con(int i) {
if(stock+i < 0) {
System.out.println("警告: 若消费" + i + "个,库存"+stock+"将不够。。。。需生产 。。。 稍等。。。 ");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stock += i;
System.out.println(Thread.currentThread().getName() + " 消费 " + i + "个, 当前库存 " + stock);
notifyAll();
}
}
/**
* 生产者
* @author JIHAN
*
*/
class Producer implements Runnable{
private Storehouse storehouse;
public Producer(Storehouse storehouse) {
this.storehouse = storehouse;
}
public void run() {
while(true) {
storehouse.produce((int)(Math.random()*10));
}
}
}
class Consumer implements Runnable{
private Storehouse storehouse;
public Consumer(Storehouse storehouse) {
this.storehouse = storehouse;
}
public void run() {
while(true) {
storehouse.con(-(int)(Math.random()*10));
}
}
}